<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="迎着朝阳的博客" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    1、Spring IoC容器 |  迎着朝阳
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="https://dxysun.com/static/yan.png" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  
<script>
var _hmt = _hmt || [];
(function() {
	var hm = document.createElement("script");
	hm.src = "https://hm.baidu.com/hm.js?aa994a8d65700b8835787dd39d079d7e";
	var s = document.getElementsByTagName("script")[0]; 
	s.parentNode.insertBefore(hm, s);
})();
</script>


</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-springForIocContainer"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  1、Spring IoC容器
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/12/13/springForIocContainer/" class="article-date">
  <time datetime="2020-12-13T08:14:53.000Z" itemprop="datePublished">2020-12-13</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/springdocs/">spring官方文档</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">61.1k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">246 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p><a id="beans"></a></p>
<p>IoC (控制反转)也称为依赖项注入(DI)</p>
<a id="more"></a>



<h2 id="1-IOC容器"><a href="#1-IOC容器" class="headerlink" title="1. IOC容器"></a><a href="#beans"></a>1. IOC容器</h2><p>这章重点说明IOC容器.</p>
<p><a id="beans-introduction"></a></p>
<h3 id="1-1-Spring-IoC容器和bean的介绍"><a href="#1-1-Spring-IoC容器和bean的介绍" class="headerlink" title="1.1. Spring IoC容器和bean的介绍"></a><a href="#beans-introduction"></a>1.1. Spring IoC容器和bean的介绍</h3><p>本章介绍Spring框架中控制反转 <a href="https://github.com/DocsHome/spring-docs/blob/master/pages/overview/overview.md#background-ioc" target="_blank" rel="noopener">Inversion of Control</a> 的实现. IOC与大家熟知的依赖注入同理， 这是一个通过依赖注入对象的过程 也就是说，它们所使用的对象，是通过构造函数参数，工厂方法的参数或这是从工厂方法的构造函数或返回值的对象实例设置的属性，然后容器在创建bean时注入这些需要的依赖。 这个过程相对普通创建对象的过程是反向的（因此称之为IoC），bean本身通过直接构造类来控制依赖关系的实例化或位置，或提供诸如服务定位器模式之类的机制。</p>
<p><code>org.springframework.beans</code> 和 <code>org.springframework.context</code> 是实现Spring IOC容器框架的基础. <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/BeanFactory.html" target="_blank" rel="noopener"><code>BeanFactory</code></a> 接口提供了一种更先进的配置机制来管理任意类型的对象. <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/ApplicationContext.html" target="_blank" rel="noopener"><code>ApplicationContext</code></a> 是<code>BeanFactory</code>的子接口. 他提供了:</p>
<ul>
<li><p>更容易与Spring的AOP特性集成</p>
</li>
<li><p>消息资源处理(用于国际化)</p>
</li>
<li><p>事件发布</p>
</li>
<li><p>应用层特定的上下文，如用于web应用程序的<code>WebApplicationContext</code>.</p>
</li>
</ul>
<p>简而言之，<code>BeanFactory</code>提供了配置框架的基本功能，<code>ApplicationContext</code>添加了更多特定于企业的功能。 <code>ApplicationContext</code>完全扩展了<code>BeanFactory</code>的功能，这些内容将在介绍Spring IoC容器的章节专门讲解。有关使用<code>BeanFactory</code>更多信息，请参见<code>BeanFactory</code>。</p>
<p>在Spring中，由Spring IOC容器管理的，构成程序的骨架的对象成为Bean。bean对象是指经过IoC容器实例化，组装和管理的对象。此外，bean就是应用程序中众多对象之一 。bean和bean的依赖由容器所使用的配置元数据反射而来。</p>
<p><a id="beans-basics"></a></p>
<h3 id="1-2-容器概述"><a href="#1-2-容器概述" class="headerlink" title="1.2. 容器概述"></a><a href="#beans-basics"></a>1.2. 容器概述</h3><p><code>org.springframework.context.ApplicationContext</code>是Spring IoC容器实现的代表，它负责实例化，配置和组装Bean。容器通过读取配置元数据获取有关实例化、配置和组装哪些对象的说明 。配置元数据可以使用XML、Java注解或Java代码来呈现。它允许你处理应用程序的对象与其他对象之间的互相依赖关系。</p>
<p>Spring提供了<code>ApplicationContext</code>接口的几个实现。 在独立应用程序中，通常创建<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/support/ClassPathXmlApplicationContext.html" target="_blank" rel="noopener"><code>ClassPathXmlApplicationContext</code></a>或<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/support/FileSystemXmlApplicationContext.html" target="_blank" rel="noopener"><code>FileSystemXmlApplicationContext</code></a>的实例。虽然XML一直是定义配置元数据的传统格式， 但是您可以指定容器使用Java注解或编程的方式编写元数据格式，并通过提供少量的XML配置以声明对某些额外元数据的支持。</p>
<p>在大多数应用场景中，不需要用户显式的编写代码来实例化IOC容器的一个或者多个实例。例如，在Web应用场景中，只需要在web.xml中添加大概8行简单的web描述样板就行了。（ <a href="#context-create">便捷的ApplicationContext实例化Web应用程序</a>） 如果你使用的是基于Eclipse的<a href="https://spring.io/tools/sts" target="_blank" rel="noopener">Spring Tool Suite</a>开发环境，该样板配置只需点击几下鼠标或按几下键盘就能创建了。</p>
<p>下图展示了Spring工作方式的高级视图，应用程序的类与元数据配置相互配合，这样，在<code>ApplicationContext</code>创建和初始化后，你立即拥有一个可配置的，可执行的系统或应用程序。</p>
<p><img src="https://github.com/DocsHome/spring-docs/blob/master/pages/images/container-magic.png" alt="container magic"></p>
<p>图 1. IOC容器</p>
<p><a id="beans-factory-metadata"></a></p>
<h4 id="1-2-1-配置元数据"><a href="#1-2-1-配置元数据" class="headerlink" title="1.2.1. 配置元数据"></a><a href="#beans-factory-metadata"></a>1.2.1. 配置元数据</h4><p>如上图所示，Spring IOC容器使用元数据配置这种形式，这个配置元数据表示了应用开发人员告诉Spring容器以何种方式实例化、配置和组装应用程序中的对象。</p>
<p>配置元数据通常以简单、直观的XML格式提供，本章的大部分内容都使用这种格式来说明Spring IoC容器的关键概念和特性。</p>
<p>XML并不是配置元数据的唯一方式，Spring IoC容器本身是完全与元数据配置的实际格式分离的。现在，许多开发人员选择<a href="#beans-java">基于Java的配置</a>来开发应用程序。</p>
<p>更多其他格式的元数据见:</p>
<ul>
<li><p><a href="#beans-annotation-config">基于注解的配置</a>: Spring 2.5 支持基于注解的元数据配置.</p>
</li>
<li><p><a href="#beans-java">基于Java的配置</a>: 从 Spring 3.0开始, 由Spring JavaConfig项目提供的功能已经成为Spring核心框架的一部分。因此，你可以使用Java配置来代替XML配置定义外部bean 。要使用这些新功能，请参阅 <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html" target="_blank" rel="noopener"><code>@Configuration</code></a>, <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html" target="_blank" rel="noopener"><code>@Bean</code></a>, <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Import.html" target="_blank" rel="noopener"><code>@Import</code></a>, 和 <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/DependsOn.html" target="_blank" rel="noopener"><code>@DependsOn</code></a> annotations.</p>
</li>
</ul>
<p>Spring配置至少一个（通常不止一个）由容器来管理。基于XML的元数据配置将这些bean配置为<code>&lt;bean/&gt;</code>元素，并放置于<code>&lt;bean/&gt;</code>元素内部。 典型的Java配置是在使用<code>@Configuration</code>注解过的类中，在它的方法上使用<code>@Bean</code>注解。</p>
<p>这些bean定义会对应到构成应用程序的实际对象。通常你会定义服务层对象，数据访问对象（DAOs），表示对象(如Struts <code>Action</code>的实例)，基础对象（如Hibernate 的<code>SessionFactories</code>, JMS <code>Queues</code>）。通常不会在容器中配置细粒度的域对象，但是，因为它的创建和加载通常是DAO和业务逻辑的任务。 但是，你可以使用Spring与AspectJ 集成独立于 IoC 容器来创建的对象，请参阅<a href="#aop-atconfigurable">AspectJ在Spring中进行依赖关系注入域对象</a></p>
<p>下面的示例显示了基于XML元数据配置的基本结构:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"..."</span> <span class="attr">class</span>=<span class="string">"..."</span>&gt;</span>  (1) (2)</span><br><span class="line">        <span class="comment">&lt;!-- collaborators and configuration for this bean go here --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"..."</span> <span class="attr">class</span>=<span class="string">"..."</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- collaborators and configuration for this bean go here --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- more bean definitions go here --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>1</strong></p>
<p><code>id</code> 属性是字符串 ，用来识别唯一的bean定义.</p>
<p><strong>2</strong></p>
<p><code>class</code> 属性定义了bean的类型，使用全类名.</p>
<p><code>id</code>属性的值是指引用协作对象（在这个例子没有显示用于引用协作对象的XML）。请参阅<a href="#beans-dependencies">依赖</a>获取更多信息</p>
<p><a id="beans-factory-instantiation"></a></p>
<h4 id="1-2-2-实例化容器"><a href="#1-2-2-实例化容器" class="headerlink" title="1.2.2. 实例化容器"></a><a href="#beans-factory-instantiation"></a>1.2.2. 实例化容器</h4><p>提供给ApplicationContext构造函数的路径就是实际的资源字符串，使容器能从各种外部资源(如本地文件系统、Java类路径等)装载元数据配置。</p>
<pre><code>ApplicationContext context = new ClassPathXmlApplicationContext(&quot;services.xml&quot;, &quot;daos.xml&quot;);</code></pre><p>当你了解Spring IoC容器，你可能想知道更多关于Spring的抽象资源（详细描述<a href="#resources">资源</a>）它提供了一种方便的，由URI语法定义的位置读取InputStream描述的方式 ，资源路径被用于构建应用程序上下文<a href="#resources-app-ctx">应用环境和资源路径</a></p>
<p>下面的例子显示了服务层对象(<code>services.xml</code>)配置文件::</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- services --&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"petStore"</span> <span class="attr">class</span>=<span class="string">"org.springframework.samples.jpetstore.services.PetStoreServiceImpl"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"accountDao"</span> <span class="attr">ref</span>=<span class="string">"accountDao"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"itemDao"</span> <span class="attr">ref</span>=<span class="string">"itemDao"</span>/&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- additional collaborators and configuration for this bean go here --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- more bean definitions for services go here --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>下面的示例显示了数据访问对象（<code>daos.xml</code>）配置文件:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"accountDao"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">"org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- additional collaborators and configuration for this bean go here --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"itemDao"</span> <span class="attr">class</span>=<span class="string">"org.springframework.samples.jpetstore.dao.jpa.JpaItemDao"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- additional collaborators and configuration for this bean go here --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- more bean definitions for data access objects go here --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在上面的例子中，服务层由PetStoreServiceImpl类，两个数据访问对象JpaAccountDao类和JpaItemDao类（基于JPA对象/关系映射标准）组成 property name元素是指JavaBean属性的名称，而ref元素引用另一个bean定义的名称。id和ref元素之间的这种联系表达了组合对象之间的相互依赖关系。有关对象间的依赖关系，请参阅<a href="#beans-dependencies">依赖</a> .</p>
<p><a id="beans-factory-xml-import"></a></p>
<h5 id="组合基于XML的元数据配置"><a href="#组合基于XML的元数据配置" class="headerlink" title="组合基于XML的元数据配置"></a><a href="#beans-factory-xml-import"></a>组合基于XML的元数据配置</h5><p>使用XML配置，可以让bean定义分布在多个XML文件上，这种方法直观优雅清晰明显。通常，每个单独的XML配置文件代表架构中的一个逻辑层或模块。</p>
<p>你可以使用应用程序上下文构造函数从所有这些XML片段加载bean定义，这个构造函数可以输入多个资源位置，<a href="#beans-factory-instantiation">如上一节所示</a>。 或者，使用<code>&lt;import/&gt;</code>元素也可以从另一个（或多个）文件加载bean定义。例如：</p>
<pre><code>&lt;beans&gt;
    &lt;import resource=&quot;services.xml&quot;/&gt;
    &lt;import resource=&quot;resources/messageSource.xml&quot;/&gt;
    &lt;import resource=&quot;/resources/themeSource.xml&quot;/&gt;

    &lt;bean id=&quot;bean1&quot; class=&quot;...&quot;/&gt;
    &lt;bean id=&quot;bean2&quot; class=&quot;...&quot;/&gt;
&lt;/beans&gt;</code></pre><p>上面的例子中，使用了3个文件：<code>services.xml</code>, <code>messageSource.xml</code>, 和 <code>themeSource.xml</code>来加载外部Bean的定义。 导入文件采用的都是相对路径，因此<code>services.xml</code>必须和导入文件位于同一目录或类路径中，而<code>messageSource.xml</code> 和 <code>themeSource.xml</code> 必须在导入文件的资源位置中。正如你所看到的，前面的斜线将会被忽略，但考虑到这些路径是相对的，最佳的使用是不用斜线的。 这个XML文件的内容都会被导入，包括顶级的 <code>&lt;beans/&gt;</code>元素，但必须遵循Spring Schema定义XML bean定义的规则 。</p>
<p>这种相对路径的配置是可行的，但不推荐这样做，引用在使用相对于”../“路径的父目录文件中，这样做会对当前应用程序之外的文件产生依赖关系。 特别是对于<code>classpath:</code>: URLs(例如<code>classpath:../services.xml</code>)，不建议使用此引用，因为在该引用中，运行时解析过程选择“最近的”classpath根目录，然后查看其父目录。 类路径的变化或者选择了不正确的目录都会导致此配置不可用。</p>
<p>您可以使用完全限定的资源位置而不是相对路径:例如，<code>file:C:/config/services.xml</code>或者<code>classpath:/config/services.xml</code>.。 但是，请注意，您正在将应用程序的配置与特定的绝对位置耦合。通常会选取间接的方式应对这种绝对路径，例如使用占位符“${…}”来解决对JVM系统属性的引用。</p>
<p>import 是由bean命名空间本身提供的功能。在Spring提供的XML命名空间中，如“<code>context</code>”和“<code>util</code>”命名空间，可以用于对普通bean定义进行更高级的功能配置。</p>
<p><a id="groovy-bean-definition-dsl"></a></p>
<h5 id="DSL定义Groovy-Bean"><a href="#DSL定义Groovy-Bean" class="headerlink" title="DSL定义Groovy Bean"></a><a href="#groovy-bean-definition-dsl"></a>DSL定义Groovy Bean</h5><p>作为从外部配置元数据的另一个示例，bean定义也可以使用Spring的Groovy DSL来定义。Grails框架有此配置实例，通常， 可以在具有以下结构的”.groovy”文件中配置bean定义。例如：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">beans &#123;</span><br><span class="line">    dataSource(BasicDataSource) &#123;</span><br><span class="line">        driverClassName = <span class="string">"org.hsqldb.jdbcDriver"</span></span><br><span class="line">        url = <span class="string">"jdbc:hsqldb:mem:grailsDB"</span></span><br><span class="line">        username = <span class="string">"sa"</span></span><br><span class="line">        password = <span class="string">""</span></span><br><span class="line">        settings = [<span class="string">mynew:</span><span class="string">"setting"</span>]</span><br><span class="line">    &#125;</span><br><span class="line">    sessionFactory(SessionFactory) &#123;</span><br><span class="line">        dataSource = dataSource</span><br><span class="line">    &#125;</span><br><span class="line">    myService(MyService) &#123;</span><br><span class="line">        nestedBean = &#123; AnotherBean bean -&gt;</span><br><span class="line">            dataSource = dataSource</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这种配置风格在很大程度上等价于XML bean定义，甚至支持Spring的XML配置名称空间。它还允许通过<code>importBeans</code>指令导入XML bean定义文件。</p>
<p><a id="beans-factory-client"></a></p>
<h4 id="1-2-3-使用容器"><a href="#1-2-3-使用容器" class="headerlink" title="1.2.3. 使用容器"></a><a href="#beans-factory-client"></a>1.2.3. 使用容器</h4><p><code>ApplicationContext</code>是能够创建bean定义以及处理相互依赖关系的高级工厂接口，使用方法<code>T getBean(String name, Class&lt;T&gt; requiredType)</code>获取容器实例。</p>
<p><code>ApplicationContext</code>可以读取bean定义并访问它们 如下 :</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// create and configure beans</span></span><br><span class="line">ApplicationContext context = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"services.xml"</span>, <span class="string">"daos.xml"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// retrieve configured instance</span></span><br><span class="line">PetStoreService service = context.getBean(<span class="string">"petStore"</span>, PetStoreService<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// use configured instance</span></span><br><span class="line">List&lt;String&gt; userList = service.getUsernameList();</span><br></pre></td></tr></table></figure>

<p>使用Groovy配置引导看起来非常相似，只是用到不同的上下文实现类：它是Groovy感知的（但也需理解XML bean定义） 如下:</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ApplicationContext context = <span class="keyword">new</span> GenericGroovyApplicationContext(<span class="string">"services.groovy"</span>, <span class="string">"daos.groovy"</span>);</span><br></pre></td></tr></table></figure>

<p>最灵活的变体是<code>GenericApplicationContext</code>，例如读取XML文件的<code>XmlBeanDefinitionReader</code>。如下面的示例所示:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">GenericApplicationContext context = <span class="keyword">new</span> GenericApplicationContext();</span><br><span class="line"><span class="keyword">new</span> XmlBeanDefinitionReader(context).loadBeanDefinitions(<span class="string">"services.xml"</span>, <span class="string">"daos.xml"</span>);</span><br><span class="line">context.refresh();</span><br></pre></td></tr></table></figure>

<p>您还可以为Groovy文件使用<code>GroovyBeanDefinitionReader</code>，如下面的示例所示:</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">GenericApplicationContext context = <span class="keyword">new</span> GenericApplicationContext();</span><br><span class="line"><span class="keyword">new</span> GroovyBeanDefinitionReader(context).loadBeanDefinitions(<span class="string">"services.groovy"</span>, <span class="string">"daos.groovy"</span>);</span><br><span class="line">context.refresh();</span><br></pre></td></tr></table></figure>

<p>这一类的读取可以在同一个 <code>ApplicationContext</code>上混合使用，也可以自动匹配，如果需要可以从不同的配置源读取bean定义。</p>
<p>您可以使用 <code>getBean</code>来获取bean实例， <code>ApplicationContext</code>接口也可以使用其他的方法来获取bean。但是在理想情况下，应用程序代码永远不应该使用它们。 事实上，你的应用程序代码也不应该调用的<code>getBean()</code>方法，因此对Spring API没有依赖。例如，Spring与Web框架的集成为各种Web框架组件(如控制器和JSF管理bean） 提供了依赖项注入功能，从而允许开发者通过元数据声明对特定bean的依赖(例如，自动注解）。</p>
<p><a id="beans-definition"></a></p>
<h3 id="1-3-Bean-的概述"><a href="#1-3-Bean-的概述" class="headerlink" title="1.3. Bean 的概述"></a><a href="#beans-definition"></a>1.3. Bean 的概述</h3><p>Spring IoC容器管理一个或多个bean。这些bean是由您提供给容器的元数据配置创建的(例如，XML <code>&lt;bean/&gt;</code>定义的形式)。</p>
<p>在容器内部，这些bean定义表示为<code>BeanDefinition</code>对象，其中包含（其他信息）以下元数据</p>
<ul>
<li><p>限定包类名称: 通常，定义的bean的实际实现类。</p>
</li>
<li><p>bean行为配置元素, 定义Bean的行为约束(例如作用域，生命周期回调等等）</p>
</li>
<li><p>bean需要引用其他bean来完成工作. 这些引用也称为协作或依赖关系.</p>
</li>
<li><p>其他配置用于新对象的创建，例如使用bean的数量来管理连接池，或者限制池的大小。</p>
</li>
</ul>
<p>以下是每个bean定义的属性:</p>
<p>Table 1. Bean的定义  </p>
<table>
<thead>
<tr>
<th>Property</th>
<th>对应的章节名</th>
</tr>
</thead>
<tbody><tr>
<td>Class</td>
<td><a href="#beans-factory-class">实例化Bean</a></td>
</tr>
<tr>
<td>Name</td>
<td><a href="#beans-beanname">命名Bean</a></td>
</tr>
<tr>
<td>Scope</td>
<td><a href="#beans-factory-scopes">Bean 的作用域</a></td>
</tr>
<tr>
<td>Constructor arguments</td>
<td><a href="#beans-factory-collaborators">依赖注入</a></td>
</tr>
<tr>
<td>Properties</td>
<td><a href="#beans-factory-collaborators">依赖注入</a></td>
</tr>
<tr>
<td>Autowiring mode</td>
<td><a href="#beans-factory-autowire">自动装配</a></td>
</tr>
<tr>
<td>Lazy initialization mode</td>
<td><a href="#beans-factory-lazy-init">懒加载Bean</a></td>
</tr>
<tr>
<td>Initialization method</td>
<td><a href="#beans-factory-lifecycle-initializingbean">初始化方法回调</a></td>
</tr>
<tr>
<td>Destruction method</td>
<td><a href="#beans-factory-lifecycle-disposablebean">销毁方法回调</a></td>
</tr>
</tbody></table>
<p>除了bean定义包含如何创建特定的bean的信息外，<code>ApplicationContext</code>实现还允许用户在容器中注册现有的、已创建的对象。 通过<code>getBeanFactory()</code>访问到返回值为<code>DefaultListableBeanFactory</code>的实现的ApplicationContext的BeanFactory <code>DefaultListableBeanFactory</code>支持通过<code>registerSingleton(..)</code>和<code>registerBeanDefinition(..)</code>方法来注册对象。 然而，典型的应用程序只能通过元数据配置来定义bean。</p>
<p>为了让容器正确推断它们在自动装配和其它内置步骤，需要尽早注册Bean的元数据和手动使用单例的实例。虽然覆盖现有的元数据和现有的单例实例在某种程度上是支持的， 但是新bean在运行时(同时访问动态工厂）注册官方并不支持，可能会导致并发访问异常、bean容器中的不一致状态，或者两者兼有。</p>
<p><a id="beans-beanname"></a></p>
<h4 id="1-3-1-命名bean"><a href="#1-3-1-命名bean" class="headerlink" title="1.3.1. 命名bean"></a><a href="#beans-beanname"></a>1.3.1. 命名bean</h4><p>每个bean都有一个或多个标识符，这些标识符在容器托管时必须是唯一的。bean通常只有一个标识符，但如果需要到的标识不止一个时，可以考虑使用别名。</p>
<p>在基于XML的配置中，开发者可以使用<code>id</code>属性，name属性或两者都指定bean的标识符。 <code>id</code>属性允许您指定一个<code>id</code>，通常这些名字使用字母和数字的组合(例如’myBean’, ‘someService’，等等），但也可以包含特殊字符。 如果你想使用bean别名，您可以在name属性上定义，使用逗号(<code>,</code>），分号(<code>;</code>)，或白色空格进行分隔。由于历史因素， 请注意，在Spring 3.1之前的版本中，id属性被定义为<code>xsd:ID</code>类型，它会限制某些字符。从3.1开始，它被定义为<code>xsd:string</code>类型。请注意，由于bean <code>id</code>的唯一性，他仍然由容器执行，不再由XML解析器执行。</p>
<p>您也无需提供bean的<code>name</code>或 <code>id</code>，如果没有显式地提供<code>name</code>或 <code>id</code>，容器会给bean生成唯一的名称。 然而，如果你想引用bean的名字，可以使用ref元素或使用<a href="#beans-servicelocator">Service Locator</a>（服务定位器）来进行查找（此时必须提供名称）。 不使用名称的情况有： <a href="#beans-inner-beans">内部bean</a>和<a href="#beans-factory-autowire">自动装配的协作者</a></p>
<p>Bean 的命名约定</p>
<p>bean的命名是按照标准的Java字段名称命名来进行的。也就是说，bean名称开始需要以小写字母开头，后面采用“驼峰式”的方法。 例如<code>accountManager</code>,<code>accountService</code>, <code>userDao</code>, <code>loginController</code>等。</p>
<p>一致的beans命名能够让配置更方便阅读和理解，如果你正在使用Spring AOP，当你通过bean名称应用到通知时，这种命名方式会有很大的帮助。</p>
<p>在类路径中进行组件扫描时， Spring 会根据上面的规则为未命名的组件生成 bean 名称，规则是：采用简单的类名，并将其初始字符转化为小写字母。 然而，在特殊情况下，当有一个以上的字符，同时第一个和第二个字符都是大写时，原来的规则仍然应该保留。这些规则与Java中定义实例的相同。 例如Spring使用的<code>java.beans.Introspector.decapitalize</code> 类。</p>
<p><a id="beans-beanname-alias"></a></p>
<h5 id="为外部定义的bean起别名"><a href="#为外部定义的bean起别名" class="headerlink" title="为外部定义的bean起别名"></a><a href="#beans-beanname-alias"></a>为外部定义的bean起别名</h5><p>在对bean定义时，除了使用<code>id</code>属性指定唯一的名称外，还可以提供多个别名，这需要通过<code>name</code>属性指定。 所有这个名称都会指向同一个bean，在某些情况下提供别名非常有用，例如为了让应用每一个组件都能更容易的对公共组件进行引用。</p>
<p>然而，在定义bean时就指定所有的别名并不是很恰当的。有时期望能够在当前位置为那些在别处定义的bean引入别名。在XML配置文件中， 可以通过<code>&lt;alias/&gt;</code>元素来定义bean别名，例如：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">alias</span> <span class="attr">name</span>=<span class="string">"fromName"</span> <span class="attr">alias</span>=<span class="string">"toName"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>上面示例中，在同一个容器中名为<code>fromName</code> 的bean定义，在增加别名定义后，也可以使用<code>toName</code>来引用。</p>
<p>例如，在子系统A中通过名字<code>subsystemA-dataSource</code>配置的数据源。在子系统B中可能通过名字 <code>subsystemB-dataSource</code>来引用。 当两个子系统构成主应用的时候，主应用可能通过名字<code>myApp-dataSource</code>引用数据源，将全部三个名字引用同一个对象，你可以将下面的别名定义添加到应用配置中：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">alias</span> <span class="attr">name</span>=<span class="string">"subsystemA-dataSource"</span> <span class="attr">alias</span>=<span class="string">"subsystemB-dataSource"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">alias</span> <span class="attr">name</span>=<span class="string">"subsystemA-dataSource"</span> <span class="attr">alias</span>=<span class="string">"myApp-dataSource"</span> /&gt;</span></span><br></pre></td></tr></table></figure>

<p>现在，每个组件和主应用程序都可以通过一个唯一的名称引用dataSource，并保证不与任何其他定义冲突（有效地创建命名空间），但它们引用相同的bean。 .</p>
<p>Java配置</p>
<p>如果你是用java配置， <code>@Bean</code>可以用来提供别名，详情见<a href="#beans-java-bean-annotation">使用<code>@Bean</code> 注解。</a></p>
<p><a id="beans-factory-class"></a></p>
<h4 id="1-3-2-实例化Bean"><a href="#1-3-2-实例化Bean" class="headerlink" title="1.3.2. 实例化Bean"></a><a href="#beans-factory-class"></a>1.3.2. 实例化Bean</h4><p>bean定义基本上就是用来创建一个或多个对象的配置，当需要bean的时候，容器会查找配置并且根据bean定义封装的元数据来创建（或获取）实际对象。</p>
<p>如果你使用基于XML的配置，那么可以在<code>&lt;bean/&gt;</code> 元素中通过 <code>class</code>属性来指定对象类型。 class属性实际上就是<code>BeanDefinition</code>实例中的<code>class</code>属性。他通常是必需的（一些例外情况，查看 <a href="#beans-factory-class-instance-factory-method">使用实例工厂方法实例化</a> 和 <a href="#beans-child-bean-definitions">Bean 定义的继承</a>)。有两种方式使用Class属性</p>
<ul>
<li><p>通常情况下，会直接通过反射调用构造方法来创建bean，这种方式与Java代码的<code>new</code>创建相似。</p>
</li>
<li><p>通过静态工厂方法创建，类中包含静态方法。通过调用静态方法返回对象的类型可能和Class一样，也可能完全不一样。</p>
</li>
</ul>
<p>内部类名</p>
<p>如果你想配置静态内部类，那么必须使用内部类的二进制名称。</p>
<p>例如，在<code>com.example</code>有个<code>SomeThing</code>类，这个类里面有个静态内部类<code>OtherThing</code>，这种情况下bean定义的class属性应该写作 <code>com.example.SomeThing$OtherThing</code>.</p>
<p>使用$字符来分隔外部类和内部类的名称</p>
<p><a id="beans-factory-class-ctor"></a></p>
<h5 id="使用构造器实例化"><a href="#使用构造器实例化" class="headerlink" title="使用构造器实例化"></a><a href="#beans-factory-class-ctor"></a>使用构造器实例化</h5><p>当您通过构造方法创建bean时，所有普通类都可以使用并与Spring兼容。也就是说，正在开发的类不需要实现任何特定接口或以特定方式编码。 只要指定bean类就足够了。但是，根据您为该特定bean使用的IoC类型，您可能需要一个默认（空）构造函数。</p>
<p>Spring IoC容器几乎可以管理您希望它管理的任何类。它不仅限于管理真正的JavaBeans。大多数Spring用户更喜欢管理那些只有一个默认构造函数（无参数） 和有合适的setter和getter方法的真实的JavaBeans，还可以在容器中放置更多的外部非bean形式（non-bean-style)类，例如：如果需要使用一个绝对违反JavaBean规范的遗留连接池时 Spring也是可以管理它的。</p>
<p>使用基于XML的配置元数据，您可以按如下方式指定bean类：:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBean"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"anotherExample"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBeanTwo"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>给构造方法指定参数以及为bean实例化设置属性将在后面的<a href="#beans-factory-collaborators">依赖注入</a>中说明。</p>
<p><a id="beans-factory-class-static-factory-method"></a></p>
<h5 id="使用静态工厂方法实例化"><a href="#使用静态工厂方法实例化" class="headerlink" title="使用静态工厂方法实例化"></a><a href="#beans-factory-class-static-factory-method"></a>使用静态工厂方法实例化</h5><p>当采用静态工厂方法创建bean时，除了需要指定class属性外，还需要通过<code>factory-method</code> 属性来指定创建bean实例的工厂方法。 Spring将会调用此方法（其可选参数接下来会介绍）返回实例对象。从这样看来，它与通过普通构造器创建类实例没什么两样。</p>
<p>下面的bean定义展示了如何通过工厂方法来创建bean实例。注意，此定义并未指定对象的返回类型，只是指定了该类包含的工厂方法，在这个例中， <code>createInstance()</code>必须是一个静态（static）的方法。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"clientService"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">class</span>=<span class="string">"examples.ClientService"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">factory-method</span>=<span class="string">"createInstance"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>以下示例显示了一个可以使用前面的bean定义的类:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClientService</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ClientService clientService = <span class="keyword">new</span> ClientService();</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">ClientService</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ClientService <span class="title">createInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> clientService;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>给工厂方法指定参数以及为bean实例设置属性的详细内容请查阅<a href="#beans-factory-properties-detailed">依赖和配置详解</a> 。</p>
<p><a id="beans-factory-class-instance-factory-method"></a></p>
<h5 id="使用实例工厂方法实例化"><a href="#使用实例工厂方法实例化" class="headerlink" title="使用实例工厂方法实例化"></a><a href="#beans-factory-class-instance-factory-method"></a>使用实例工厂方法实例化</h5><p>通过调用工厂实例的非静态方法进行实例化与通过<a href="#beans-factory-class-static-factory-method">静态工厂方法</a>实例化类似， 要使用此机制，请将class属性保留为空，并在<code>factory-bean</code>属性中指定当前（或父级或祖先）容器中bean的名称，该容器包含要调用以创建对象的实例方法。 使用<code>factory-method</code>属性设置工厂方法本身的名称。以下示例显示如何配置此类bean：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- the factory bean, which contains a method called createInstance() --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"serviceLocator"</span> <span class="attr">class</span>=<span class="string">"examples.DefaultServiceLocator"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- inject any dependencies required by this locator bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- the bean to be created via the factory bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"clientService"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">factory-bean</span>=<span class="string">"serviceLocator"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">factory-method</span>=<span class="string">"createClientServiceInstance"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>以下示例显示了相应的Java类:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultServiceLocator</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ClientService clientService = <span class="keyword">new</span> ClientServiceImpl();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ClientService <span class="title">createClientServiceInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> clientService;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>一个工厂类也可以包含多个工厂方法，如以下示例所示:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"serviceLocator"</span> <span class="attr">class</span>=<span class="string">"examples.DefaultServiceLocator"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- inject any dependencies required by this locator bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"clientService"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">factory-bean</span>=<span class="string">"serviceLocator"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">factory-method</span>=<span class="string">"createClientServiceInstance"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"accountService"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">factory-bean</span>=<span class="string">"serviceLocator"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">factory-method</span>=<span class="string">"createAccountServiceInstance"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>以下示例显示了相应的Java类:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultServiceLocator</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ClientService clientService = <span class="keyword">new</span> ClientServiceImpl();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> AccountService accountService = <span class="keyword">new</span> AccountServiceImpl();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ClientService <span class="title">createClientServiceInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> clientService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> AccountService <span class="title">createAccountServiceInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> accountService;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这种方法表明可以通过依赖注入（DI）来管理和配置工厂bean本身。请参阅详细信息中的<a href="#beans-factory-properties-detailed">依赖和配置详解</a>。</p>
<p>在Spring文档中，“factory bean”是指在Spring容器中配置并通过<a href="#beans-factory-class-instance-factory-method">实例</a> 或 <a href="#beans-factory-class-static-factory-method">静态工厂方法</a> 创建对象的bean。相比之下，FactoryBean（注意大小写）是指Spring特定的<a href="#beans-factory-extension-factorybean"><code>FactoryBean</code></a>。</p>
<p><a id="beans-dependencies"></a></p>
<h3 id="1-4-依赖"><a href="#1-4-依赖" class="headerlink" title="1.4. 依赖"></a><a href="#beans-dependencies"></a>1.4. 依赖</h3><p>一般情况下企业应用不会只有一个对象（Spring Bean），甚至最简单的应用都需要多个对象协同工作。下一节将解释如何从定义单个Bean到让多个Bean协同工作。</p>
<p><a id="beans-factory-collaborators"></a></p>
<h4 id="1-4-1-依赖注入"><a href="#1-4-1-依赖注入" class="headerlink" title="1.4.1. 依赖注入"></a><a href="#beans-factory-collaborators"></a>1.4.1. 依赖注入</h4><p>依赖注入是让对象只通过构造参数、工厂方法的参数或者配置的属性来定义他们的依赖的过程。这些依赖也是其他对象所需要协同工作的对象， 容器会在创建Bean的时候注入这些依赖。整个过程完全反转了由Bean自己控制实例化或者依赖引用，所以这个过程也称之为“控制反转”</p>
<p>当使用了依赖注入的特性以后，会让开发者更容易管理和解耦对象之间的依赖，使代码变得更加简单。对象之间不再关注依赖，也不需要知道依赖类的位置。如此一来，开发的类更易于测试 尤其是当开发者的依赖是接口或者抽象类的情况时，开发者可以轻易地在单元测试中mock对象。</p>
<p>依赖注入主要使用两种方式，一种是<a href="#beans-constructor-injection">基于构造函数的注入</a>，另一种的<a href="#beans-setter-injection">基于Setter方法的依赖注入</a>。</p>
<p><a id="beans-constructor-injection"></a></p>
<h5 id="基于构造函数的依赖注入"><a href="#基于构造函数的依赖注入" class="headerlink" title="基于构造函数的依赖注入"></a><a href="#beans-constructor-injection"></a>基于构造函数的依赖注入</h5><p>基于构造函数的依赖注入是由IoC容器来调用类的构造函数，构造函数的参数代表这个Bean所依赖的对象。构造函数的依赖注入与调用带参数的静态工厂方法基本一样。 调用具有特定参数的静态工厂方法来构造bean几乎是等效的，本讨论同样处理构造函数和静态工厂方法的参数。下面的例子展示了一个通过构造函数来实现依赖注入的类。:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// the SimpleMovieLister has a dependency on a MovieFinder</span></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// a constructor so that the Spring container can inject a MovieFinder</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SimpleMovieLister</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// business logic that actually uses the injected MovieFinder is omitted...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>请注意，这个类没有什么特别之处。 它是一个POJO，它不依赖于容器特定的接口，基类或注解。</p>
<p><a id="beans-factory-ctor-arguments-resolution"></a></p>
<h6 id="解析构造器参数"><a href="#解析构造器参数" class="headerlink" title="解析构造器参数"></a><a href="#beans-factory-ctor-arguments-resolution"></a>解析构造器参数</h6><p>构造函数的参数解析是通过参数的类型来匹配的。如果在Bean的构造函数参数不存在歧义，那么构造器参数的顺序也就是就是这些参数实例化以及装载的顺序。参考如下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> x.y;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThingOne</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ThingOne</span><span class="params">(ThingTwo thingTwo, ThingThree thingThree)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>假设<code>ThingTwo</code>和<code>ThingThree</code>类与继承无关，也没有什么歧义。下面的配置完全可以工作正常。开发者无需再到<code>&lt;constructor-arg/&gt;</code>元素中指定构造函数参数的index或type</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"thingOne"</span> <span class="attr">class</span>=<span class="string">"x.y.ThingOne"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"thingTwo"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"thingThree"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"thingTwo"</span> <span class="attr">class</span>=<span class="string">"x.y.ThingTwo"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"thingThree"</span> <span class="attr">class</span>=<span class="string">"x.y.ThingThree"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>当引用另一个bean时，如果类型是已知的，匹配就会工作正常（与前面的示例一样）。当使用简单类型的时候（例如<code>&lt;value&gt;true&lt;/value&gt;</code>）， Spring IoC容器无法判断值的类型，所以也是无法匹配的，考虑代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> examples;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExampleBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Number of years to calculate the Ultimate Answer</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> years;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// The Answer to Life, the Universe, and Everything</span></span><br><span class="line">    <span class="keyword">private</span> String ultimateAnswer;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ExampleBean</span><span class="params">(<span class="keyword">int</span> years, String ultimateAnswer)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.years = years;</span><br><span class="line">        <span class="keyword">this</span>.ultimateAnswer = ultimateAnswer;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>构造函数参数类型匹配</p>
<p>在前面的场景中，如果使用 type 属性显式指定构造函数参数的类型，则容器可以使用与简单类型的类型匹配。如下例所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">type</span>=<span class="string">"int"</span> <span class="attr">value</span>=<span class="string">"7500000"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">type</span>=<span class="string">"java.lang.String"</span> <span class="attr">value</span>=<span class="string">"42"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>构造函数参数索引</p>
<p>您可以使用<code>index</code>属性显式指定构造函数参数的索引，如以下示例所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">index</span>=<span class="string">"0"</span> <span class="attr">value</span>=<span class="string">"7500000"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">index</span>=<span class="string">"1"</span> <span class="attr">value</span>=<span class="string">"42"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>除了解决多个简单值的歧义之外，指定索引还可以解决构造函数具有相同类型的两个参数的歧义。</p>
<p>index 从0开始。</p>
<p>构造函数参数名称</p>
<p>您还可以使用构造函数参数名称消除歧义，如以下示例所示：:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">name</span>=<span class="string">"years"</span> <span class="attr">value</span>=<span class="string">"7500000"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">name</span>=<span class="string">"ultimateAnswer"</span> <span class="attr">value</span>=<span class="string">"42"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>需要注意的是，解析这个配置的代码必须启用了调试标记来编译，这样Spring才可以从构造函数查找参数名称。开发者也可以使用<a href="https://download.oracle.com/javase/6/docs/api/java/beans/ConstructorProperties.html" target="_blank" rel="noopener">@ConstructorProperties</a>注解来显式声明构造函数的名称。 例如下面代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> examples;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExampleBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Fields omitted</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@ConstructorProperties</span>(&#123;<span class="string">"years"</span>, <span class="string">"ultimateAnswer"</span>&#125;)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ExampleBean</span><span class="params">(<span class="keyword">int</span> years, String ultimateAnswer)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.years = years;</span><br><span class="line">        <span class="keyword">this</span>.ultimateAnswer = ultimateAnswer;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-setter-injection"></a></p>
<h5 id="基于setter方法的依赖注入"><a href="#基于setter方法的依赖注入" class="headerlink" title="基于setter方法的依赖注入"></a><a href="#beans-setter-injection"></a>基于setter方法的依赖注入</h5><p>基于setter函数的依赖注入是让容器调用拥有Bean的无参构造函数，或者<code>无参静态工厂方法</code>，然后再来调用setter方法来实现依赖注入。</p>
<p>下面的例子展示了使用setter方法进行的依赖注入的过程。其中类对象只是简单的POJO，它不依赖于容器特定的接口，基类或注解。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// the SimpleMovieLister has a dependency on the MovieFinder</span></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// a setter method so that the Spring container can inject a MovieFinder</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// business logic that actually uses the injected MovieFinder is omitted...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>ApplicationContext</code>所管理Bean同时支持基于构造函数和基于setter方法的依赖注入，同时也支持使用setter方法在通过构造函数注入依赖之后再次注入依赖。 开发者在<code>BeanDefinition</code>中可以使用<code>PropertyEditor</code>实例来自由选择注入方式。然而，大多数的开发者并不直接使用这些类，而是更喜欢使用XML配置来进行bean定义， 或者基于注解的组件（例如使用 <code>@Component</code>,<code>@Controller</code>等），或者在配置了<code>@Configuration</code>的类上面使用<code>@Bean</code>的方法。 然后，这些源在内部转换为 <code>BeanDefinition</code>的实例，并用于加载整个Spring IoC容器实例。</p>
<p>如何选择基于构造器和基于setter方法?</p>
<p>因为开发者可以混用两种依赖注入方式，两种方式用于处理不同的情况：必要的依赖通常通过构造函数注入，而可选的依赖则通过setter方法注入。其中，在setter方法上添加<a href="#beans-required-annotation">@Required</a> 注解可用于构造必要的依赖。</p>
<p>Spring团队推荐使用基于构造函数的注入，因为这种方式会促使开发者将组件开发成不可变对象并且确保注入的依赖不为<code>null</code>。另外，基于构造函数的注入的组件被客户端调用的时候也已经是完全构造好的 。当然，从另一方面来说，过多的构造函数参数也是非常糟糕的代码方式，这种方式说明类附带了太多的功能，最好重构将不同职能分离。</p>
<p>基于setter的注入只用于可选的依赖，但是也最好配置一些合理的默认值。否则，只能对代码的依赖进行非null值检查了。基于setter方法的注入有一个便利之处是：对象可以重新配置和重新注入。 因此，使用setter注入管理 <a href="https://github.com/DocsHome/spring-docs/blob/master/pages/integration/integration.md#jmx" target="_blank" rel="noopener">JMX MBeans</a> 是很方便的</p>
<p>依赖注入的两种风格适合大多数的情况，但是在使用第三方库的时候，开发者可能并没有源码，那么就只能使用基于构造函数的依赖注入了。</p>
<p><a id="beans-dependency-resolution"></a></p>
<h5 id="决定依赖的过程"><a href="#决定依赖的过程" class="headerlink" title="决定依赖的过程"></a><a href="#beans-dependency-resolution"></a>决定依赖的过程</h5><p>容器解析Bean的过程如下:</p>
<ul>
<li><p>创建并根据描述的元数据来实例化<code>ApplicationContext</code>，元数据配置可以是XML文件、Java代码或者注解。</p>
</li>
<li><p>每一个Bean的依赖都通过构造函数参数或属性，或者静态工厂方法的参数等等来表示。这些依赖会在Bean创建的时候装载和注入</p>
</li>
<li><p>每一个属性或者构造函数的参数都是真实定义的值或者引用容器其他的Bean.</p>
</li>
<li><p>每一个属性或者构造参数可以根据指定的类型转换为所需的类型。Spring也可以将String转成默认的Java内置类型。例如<code>int</code>, <code>long</code>, <code>String</code>, <code>boolean</code>等 。</p>
</li>
</ul>
<p>Spring容器会在容器创建的时候针对每一个Bean进行校验。但是Bean的属性在Bean没有真正创建之前是不会进行配置的，单例类型的Bean是容器创建的时候配置成预实例状态的。 <a href="#beans-factory-scopes">Bean的作用域</a>后面再说，其他的Bean都只有在请求的时候，才会创建，显然创建Bean对象会有一个依赖顺序图，这个图表示Bean之间的依赖关系。 容器根据此来决定创建和配置Bean的顺序。</p>
<p>循环依赖</p>
<p>如果开发者主要使用基于构造函数的依赖注入，那么很有可能出现循环依赖的情况。</p>
<p>例如：类A在构造函数中依赖于类B的实例，而类B的构造函数又依赖类A的实例。如果这样配置类A和类B相互注入的话，Spring IoC容器会发现这个运行时的循环依赖， 并且抛出<code>BeanCurrentlyInCreationException</code>。</p>
<p>开发者可以选择setter方法来配置依赖注入，这样就不会出现循环依赖的情况。或者根本就不使用基于构造函数的依赖注入，而仅仅使用基于setter方法的依赖注入。 换言之，但是开发者可以将循环依赖配置为基于Setter方法的依赖注入（尽管不推荐这样做）</p>
<p>不像典型的例子（没有循环依赖的情况），bean A和bean B之间的循环依赖关系在完全初始化之前就已经将其中一个bean注入到另一个中了（典型的鸡和鸡蛋的故事）</p>
<p>你可以信任Spring做正确的事。它在容器加载时检测配置问题，例如对不存在的bean和循环依赖的引用。 当实际创建bean时，Spring会尽可能晚地设置属性并解析依赖项。这也意味着Spring容器加载正确后会在bean注入依赖出错的时候抛出异常。例如，bean抛出缺少属性或者属性不合法的异常 ，这种延迟的解析也是<code>ApplicationContext</code> 的实现会令单例Bean处于预实例化状态的原因。这样，通过<code>ApplicationContext</code>创建bean，可以在真正使用bean之前消耗一些内存代价而发现配置的问题 。开发者也可以覆盖默认的行为让单例bean延迟加载，而不总是处于预实例化状态。</p>
<p>如果不存在循环依赖的话，bean所引用的依赖会预先全部构造。举例来说，如果bean A依赖于bean B，那么Spring IoC容器会先配置bean B，然后调用bean A的setter方法来构造bean A。 换言之，bean先会实例化，然后再注入依赖，最后才是相关生命周期方法的调用（就像配置文件的<a href="#beans-factory-lifecycle-initializingbean">初始化方法</a> 或者<a href="#beans-factory-lifecycle-initializingbean">InitializingBean的回调函数</a>那样）。</p>
<p><a id="beans-some-examples"></a></p>
<h5 id="依赖注入的例子"><a href="#依赖注入的例子" class="headerlink" title="依赖注入的例子"></a><a href="#beans-some-examples"></a>依赖注入的例子</h5><p>下面的例子使用基于XML的元数据配置，然后使用setter方式进行依赖注入。下面是Spring中使用XML文件声明bean定义的片段：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBean"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- setter injection using the nested ref element --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"beanOne"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">ref</span> <span class="attr">bean</span>=<span class="string">"anotherExampleBean"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- setter injection using the neater ref attribute --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"beanTwo"</span> <span class="attr">ref</span>=<span class="string">"yetAnotherBean"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"integerProperty"</span> <span class="attr">value</span>=<span class="string">"1"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"anotherExampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.AnotherBean"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"yetAnotherBean"</span> <span class="attr">class</span>=<span class="string">"examples.YetAnotherBean"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>以下示例显示了相应的 <code>ExampleBean</code>类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExampleBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AnotherBean beanOne;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> YetAnotherBean beanTwo;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> i;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBeanOne</span><span class="params">(AnotherBean beanOne)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.beanOne = beanOne;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBeanTwo</span><span class="params">(YetAnotherBean beanTwo)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.beanTwo = beanTwo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setIntegerProperty</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.i = i;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在前面的示例中，setter被声明为与XML文件中指定的属性匹配。以下示例使用基于构造函数的DI：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBean"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- constructor injection using the nested ref element --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">ref</span> <span class="attr">bean</span>=<span class="string">"anotherExampleBean"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">constructor-arg</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- constructor injection using the neater ref attribute --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"yetAnotherBean"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">type</span>=<span class="string">"int"</span> <span class="attr">value</span>=<span class="string">"1"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"anotherExampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.AnotherBean"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"yetAnotherBean"</span> <span class="attr">class</span>=<span class="string">"examples.YetAnotherBean"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>以下示例显示了相应的<code>ExampleBean</code>类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExampleBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AnotherBean beanOne;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> YetAnotherBean beanTwo;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> i;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ExampleBean</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        AnotherBean anotherBean, YetAnotherBean yetAnotherBean, <span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.beanOne = anotherBean;</span><br><span class="line">        <span class="keyword">this</span>.beanTwo = yetAnotherBean;</span><br><span class="line">        <span class="keyword">this</span>.i = i;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>bean定义中指定的构造函数参数用作 <code>ExampleBean</code>的构造函数的参数。</p>
<p>现在考虑这个示例的变体，其中，不使用构造函数，而是告诉Spring调用静态工厂方法来返回对象的实例：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBean"</span> <span class="attr">factory-method</span>=<span class="string">"createInstance"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"anotherExampleBean"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"yetAnotherBean"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">value</span>=<span class="string">"1"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"anotherExampleBean"</span> <span class="attr">class</span>=<span class="string">"examples.AnotherBean"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"yetAnotherBean"</span> <span class="attr">class</span>=<span class="string">"examples.YetAnotherBean"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>以下示例显示了相应的<code>ExampleBean</code>类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExampleBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// a private constructor</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">ExampleBean</span><span class="params">(...)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// a static factory method; the arguments to this method can be</span></span><br><span class="line">    <span class="comment">// considered the dependencies of the bean that is returned,</span></span><br><span class="line">    <span class="comment">// regardless of how those arguments are actually used.</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExampleBean <span class="title">createInstance</span> <span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        AnotherBean anotherBean, YetAnotherBean yetAnotherBean, <span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        ExampleBean eb = <span class="keyword">new</span> ExampleBean (...);</span><br><span class="line">        <span class="comment">// some other operations...</span></span><br><span class="line">        <span class="keyword">return</span> eb;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>静态工厂方法</code>的参数由<code>&lt;constructor-arg/&gt;</code>元素提供，与实际使用的构造函数完全相同。工厂方法返回类的类型不必与包含<code>静态工厂方法</code> 的类完全相同， 尽管在本例中是这样。实例（非静态）工厂方法的使用方式也是相似的（除了使用<code>factory-bean</code>属性而不是<code>class</code>属性。因此此处不在展开讨论。</p>
<p><a id="beans-factory-properties-detailed"></a></p>
<h4 id="1-4-2-依赖和配置的细节"><a href="#1-4-2-依赖和配置的细节" class="headerlink" title="1.4.2. 依赖和配置的细节"></a><a href="#beans-factory-properties-detailed"></a>1.4.2. 依赖和配置的细节</h4><p><a href="#beans-factory-collaborators">如上一节所述</a>，您可以将bean的属性和构造函数参数定义为对其他bean的引用，或者作为其内联定义的值。Spring可以允许您在基于XML的配置元数据（定义Bean）中使用子元素<code>&lt;property/&gt;</code> and <code>&lt;constructor-arg/&gt;</code> 来达到这种目的。</p>
<p><a id="beans-value-element"></a></p>
<h5 id="直接值（基本类型，String等等）"><a href="#直接值（基本类型，String等等）" class="headerlink" title="直接值（基本类型，String等等）"></a><a href="#beans-value-element"></a>直接值（基本类型，String等等）</h5><p><code>&lt;property/&gt;</code> 元素的<code>value</code> 属性将属性或构造函数参数指定为人类可读的字符串表示形式， Spring的<a href="#core-convert-ConversionService-API">conversion service</a>用于将这些值从<code>String</code> 转换为属性或参数的实际类型。 以下示例显示了要设置的各种值：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"myDataSource"</span> <span class="attr">class</span>=<span class="string">"org.apache.commons.dbcp.BasicDataSource"</span> <span class="attr">destroy-method</span>=<span class="string">"close"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- results in a setDriverClassName(String) call --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driverClassName"</span> <span class="attr">value</span>=<span class="string">"com.mysql.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"url"</span> <span class="attr">value</span>=<span class="string">"jdbc:mysql://localhost:3306/mydb"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"root"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"masterkaoli"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>以下示例使用<a href="#beans-p-namespace">p命名空间</a>进行更简洁的XML配置：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:p</span>=<span class="string">"http://www.springframework.org/schema/p"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">    http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"myDataSource"</span> <span class="attr">class</span>=<span class="string">"org.apache.commons.dbcp.BasicDataSource"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">destroy-method</span>=<span class="string">"close"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">p:driverClassName</span>=<span class="string">"com.mysql.jdbc.Driver"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">p:url</span>=<span class="string">"jdbc:mysql://localhost:3306/mydb"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">p:username</span>=<span class="string">"root"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">p:password</span>=<span class="string">"masterkaoli"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>前面的XML更简洁。 但是因为属性的类型是在运行时确定的，而非设计时确定的。所有有可能在运行时发现拼写错误。，除非您在创建bean定义时使用支持自动属性完成的IDE（例如<a href="http://www.jetbrains.com/idea/" target="_blank" rel="noopener">IntelliJ IDEA</a> or the <a href="https://spring.io/tools/sts" target="_blank" rel="noopener">Spring Tool Suite</a>）。 所以，强烈建议使用此类IDE帮助。</p>
<p>你也可以配置一个<code>java.util.Properties</code> 的实例，如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"mappings"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">class</span>=<span class="string">"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- typed as a java.util.Properties --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"properties"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">value</span>&gt;</span></span><br><span class="line">            jdbc.driver.className=com.mysql.jdbc.Driver</span><br><span class="line">            jdbc.url=jdbc:mysql://localhost:3306/mydb</span><br><span class="line">        <span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Spring的容器会将<code>&lt;value/&gt;</code>里面的文本通过JavaBean的<code>PropertyEditor</code> 机制转换成<code>java.util.Properties</code> 实例， 这种嵌套<code>&lt;value/&gt;</code>元素的快捷方式也是Spring团队推荐使用的。</p>
<p><a id="beans-idref-element"></a></p>
<h6 id="idref-元素"><a href="#idref-元素" class="headerlink" title="idref 元素"></a><a href="#beans-idref-element"></a><code>idref</code> 元素</h6><p><code>idref</code> 元素只是一种防错方法，可以将容器中另一个bean的<code>id</code>（字符串值 - 而不是引用）传递给<code>&lt;constructor-arg/&gt;</code>或<code>&lt;property/&gt;</code>元素：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"theTargetBean"</span> <span class="attr">class</span>=<span class="string">"..."</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"theClientBean"</span> <span class="attr">class</span>=<span class="string">"..."</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"targetName"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">idref</span> <span class="attr">bean</span>=<span class="string">"theTargetBean"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>前面的bean定义代码段运行时与以下代码段完全等效：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"theTargetBean"</span> <span class="attr">class</span>=<span class="string">"..."</span> /&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"client"</span> <span class="attr">class</span>=<span class="string">"..."</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"targetName"</span> <span class="attr">value</span>=<span class="string">"theTargetBean"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Spring团队更推荐第一种方式，因为使用了<code>idref</code> 标签，它会让容器在部署阶段就对bean进行校验，以确保bean一定存在。而使用第二种方式的话，是没有任何校验的。 只有实际上引用了<code>client</code> bean的<code>targetName</code>属性，不对其值进行校验。在实例化client的时候才会被发现。如果client是<a href="#beans-factory-scopes">prototype</a>类型的Bean的话，那么类似拼写之类的错误会在容器部署以后很久才能发现。</p>
<p><code>idref</code>元素的<code>local</code>属性在Spring 4.0以后的xsd中已经不再支持了，而是使用了bean引用。如果更新了版本的话，只要将<code>idref local</code>引用都转换成<code>idref bean</code> 即可。</p>
<p>在<code>ProxyFactoryBean</code>定义中，元素所携带的值在<a href="#aop-pfb-1">AOP拦截器a&gt;的配置中很常见（至少在Spring 2.0之前的版本是这样）。在指定拦截器名称时使用<code>&lt;idref/&gt;</code> 元素可防止拦截器漏掉id或拼写错误。</a></p>
<p><a id="beans-ref-element"></a></p>
<h5 id="引用其他的Bean（装配）"><a href="#引用其他的Bean（装配）" class="headerlink" title="引用其他的Bean（装配）"></a><a href="#aop-pfb-1"></a><a href="#beans-ref-element"></a>引用其他的Bean（装配）</h5><p><code>ref</code> 元素是<code>&lt;constructor-arg/&gt;</code> 或 or <code>&lt;property/&gt;</code>定义元素中的最后一个元素。 你可以通过这个标签配置一个bean来引用另一个bean。当需要引用一个bean的时候，被引用的bean会先实例化，然后配置属性，也就是引用的依赖。如果该bean是单例bean的话 ，那么该bean会早由容器初始化。最终会引用另一个对象的所有引用，bean的范围以及校验取决于你是否有通过<code>bean</code>, <code>local,</code> or <code>parent</code> 这些属性来指定对象的id或者name属性。</p>
<p>通过指定 <code>bean</code>属性中的<code>&lt;ref/&gt;</code>元素来指定依赖是最常见的一种方式，可以引用容器或者父容器中的bean，不在同一个XML文件定义也可以引用。 其中<code>bean</code> 属性中的值可以和其他引用<code>bean</code> 中的<code>id</code>属性一致，或者和其中的某个<code>name</code> 属性一致，以下示例显示如何使用ref元素：：</p>
<pre><code>&lt;ref bean=&quot;someBean&quot;/&gt;</code></pre><p>通过指定bean的<code>parent</code>属性可以创建一个引用到当前容器的父容器之中。<code>parent</code>属性的值可以与目标bean的<code>id</code>属性一致，或者和目标bean的<code>name</code>属性中的某个一致，目标bean必须是当前引用目标bean容器的父容器 。开发者一般只有在存在层次化容器，并且希望通过代理来包裹父容器中一个存在的bean的时候才会用到这个属性。 以下一对列表显示了如何使用父属性:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- in the parent context --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"accountService"</span> <span class="attr">class</span>=<span class="string">"com.something.SimpleAccountService"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- insert dependencies as required as here --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- in the child (descendant) context --&gt;</span></span><br><span class="line">&lt;bean id="accountService" &lt;!-- bean name is the same as the parent bean --&gt;</span><br><span class="line">    class="org.springframework.aop.framework.ProxyFactoryBean"&gt;</span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"target"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">ref</span> <span class="attr">parent</span>=<span class="string">"accountService"</span>/&gt;</span> <span class="comment">&lt;!-- notice how we refer to the parent bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- insert other configuration and dependencies as required here --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>与idref标签一样，<code>ref</code>元素中的<code>local</code> 标签在xsd 4.0，以后已经不再支持了，开发者可以通过将已存在的<code>ref local</code>改为<code>ref bean</code> 来完成Spring版本升级。</p>
<p><a id="beans-inner-beans"></a></p>
<h5 id="内部bean"><a href="#内部bean" class="headerlink" title="内部bean"></a><a href="#beans-inner-beans"></a>内部bean</h5><p>定义在<code>&lt;bean/&gt;</code>元素的<code>&lt;property/&gt;</code>或者<code>&lt;constructor-arg/&gt;</code> 元素之内的bean叫做内部bean，如下例所示：:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"outer"</span> <span class="attr">class</span>=<span class="string">"..."</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- instead of using a reference to a target bean, simply define the target bean inline --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"target"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.example.Person"</span>&gt;</span> <span class="comment">&lt;!-- this is the inner bean --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"name"</span> <span class="attr">value</span>=<span class="string">"Fiona Apple"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"age"</span> <span class="attr">value</span>=<span class="string">"25"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>内部bean定义不需要定义的ID或名称。如果指定，则容器不使用此类值作为标识符。容器还会在创建时忽略<code>scope</code> 标签，因为内部bean始终是匿名的，并且始终使用外部bean创建。 开发者是无法将内部bean注入到外部bean以外的其他bean中的。</p>
<p>作为一个极端情况，可以从自定义范围接收销毁回调 ， 例如：请求范围的内部bean包含了单例bean，那么内部bean实例会绑定到包含的bean，而包含的bean允许访问request的scope生命周期。 这种场景并不常见，内部bean通常只是供给它的外部bean使用。</p>
<p><a id="beans-collection-elements"></a></p>
<h5 id="集合"><a href="#集合" class="headerlink" title="集合"></a><a href="#beans-collection-elements"></a>集合</h5><p>在<code>&lt;list/&gt;</code>, <code>&lt;set/&gt;</code>, <code>&lt;map/&gt;</code>, 和 <code>&lt;props/&gt;</code>元素中，您可以分别配置Java集合类型 <code>List</code>, <code>Set</code>, <code>Map</code>, and <code>Properties</code>的属性和参数。 以下示例显示了如何使用它们:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"moreComplexObject"</span> <span class="attr">class</span>=<span class="string">"example.ComplexObject"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- results in a setAdminEmails(java.util.Properties) call --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"adminEmails"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">props</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"administrator"</span>&gt;</span>administrator@example.org<span class="tag">&lt;/<span class="name">prop</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"support"</span>&gt;</span>support@example.org<span class="tag">&lt;/<span class="name">prop</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"development"</span>&gt;</span>development@example.org<span class="tag">&lt;/<span class="name">prop</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">props</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- results in a setSomeList(java.util.List) call --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"someList"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>a list element followed by a reference<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">ref</span> <span class="attr">bean</span>=<span class="string">"myDataSource"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- results in a setSomeMap(java.util.Map) call --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"someMap"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">map</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"an entry"</span> <span class="attr">value</span>=<span class="string">"just some string"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span> =<span class="string">"a ref"</span> <span class="attr">value-ref</span>=<span class="string">"myDataSource"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">map</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- results in a setSomeSet(java.util.Set) call --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"someSet"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">set</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>just some string<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">ref</span> <span class="attr">bean</span>=<span class="string">"myDataSource"</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>当然，map的key或者value，或者集合的value都可以配置为下列元素之一:</p>
<pre><code>bean | ref | idref | list | set | map | props | value | null</code></pre><p><a id="beans-collection-elements-merging"></a></p>
<h6 id="集合的合并"><a href="#集合的合并" class="headerlink" title="集合的合并"></a><a href="#beans-collection-elements-merging"></a>集合的合并</h6><p>Spring的容器也支持集合合并，开发者可以定义父样式的<code>&lt;list/&gt;</code>, <code>&lt;map/&gt;</code>, <code>&lt;set/&gt;</code> 或 <code>&lt;props/&gt;</code>元素， 同时有子样式的<code>&lt;list/&gt;</code>, <code>&lt;map/&gt;</code>, <code>&lt;set/&gt;</code> 或 <code>&lt;props/&gt;</code>元素。也就是说，子集合的值是父元素和子元素集合的合并值。</p>
<p>有关合并的这一节讨论父子bean机制，不熟悉父和子bean定义的读者可能希望在继续之前阅读<a href="#beans-child-bean-definitions">相关部分</a>。</p>
<p>以下示例演示了集合合并：:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"parent"</span> <span class="attr">abstract</span>=<span class="string">"true"</span> <span class="attr">class</span>=<span class="string">"example.ComplexObject"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"adminEmails"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">props</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"administrator"</span>&gt;</span>administrator@example.com<span class="tag">&lt;/<span class="name">prop</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"support"</span>&gt;</span>support@example.com<span class="tag">&lt;/<span class="name">prop</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">props</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"child"</span> <span class="attr">parent</span>=<span class="string">"parent"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"adminEmails"</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!-- the merge is specified on the child collection definition --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">props</span> <span class="attr">merge</span>=<span class="string">"true"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"sales"</span>&gt;</span>sales@example.com<span class="tag">&lt;/<span class="name">prop</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">prop</span> <span class="attr">key</span>=<span class="string">"support"</span>&gt;</span>support@example.co.uk<span class="tag">&lt;/<span class="name">prop</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">props</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>请注意，在<code>child</code> bean 定义的<code>adminEmails</code>中的<code>&lt;props/&gt;</code>使用<code>merge=true</code> 属性。 当容器解析并实例化<code>child</code> bean时，生成的实例有一个<code>adminEmails</code>属性集合， 其实例中包含的<code>adminEmails</code>集合就是child的<code>adminEmails</code>以及parent的<code>adminEmails</code>集合。以下清单显示了结果： :</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">administrator&#x3D;administrator@example.com</span><br><span class="line">sales&#x3D;sales@example.com</span><br><span class="line">support&#x3D;support@example.co.uk</span><br></pre></td></tr></table></figure>

<p>子<code>属性</code>集合的值集继承父<code>&lt;props/&gt;</code>的所有属性元素，子值的<code>支持</code>值覆盖父集合中的值。</p>
<p>这个合并的行为和<code>&lt;list/&gt;</code>, <code>&lt;map/&gt;</code>, 和 <code>&lt;set/&gt;</code>之类的集合类型的行为是类似的。<code>List</code> 在特定例子中，与List集合类型类似， 有着隐含的 <code>ordered</code>概念。所有的父元素里面的值，是在所有子元素的值之前配置的。但是像<code>Map</code>, <code>Set</code>, 和 <code>Properties</code>的集合类型，是不存在顺序的。</p>
<p><a id="beans-collection-merge-limitations"></a></p>
<h6 id="集合合并的限制"><a href="#集合合并的限制" class="headerlink" title="集合合并的限制"></a><a href="#beans-collection-merge-limitations"></a>集合合并的限制</h6><p>您不能合并不同类型的集合（例如要将<code>Map</code> 和<code>List</code>合并是不可能的）。如果开发者硬要这样做就会抛出异常， <code>merge</code>的属性是必须特指到更低级或者继承的子节点定义上， 特指merge属性到父集合的定义上是冗余的，而且在合并上也没有任何效果。</p>
<p><a id="beans-collection-elements-strongly-typed"></a></p>
<h6 id="强类型的集合"><a href="#强类型的集合" class="headerlink" title="强类型的集合"></a><a href="#beans-collection-elements-strongly-typed"></a>强类型的集合</h6><p>在Java 5以后，开发者可以使用强类型的集合了。也就是，开发者可以声明<code>Collection</code>类型，然后这个集合只包含<code>String</code>元素（举例来说）。 如果开发者通过Spring来注入强类型的Collection到bean中，开发者就可以利用Spring的类型转换支持来做到 以下Java类和bean定义显示了如何执行此操作:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public class SomeClass &#123;</span><br><span class="line"></span><br><span class="line">    private Map<span class="tag">&lt;<span class="name">String,</span> <span class="attr">Float</span>&gt;</span> accounts;</span><br><span class="line"></span><br><span class="line">    public void setAccounts(Map<span class="tag">&lt;<span class="name">String,</span> <span class="attr">Float</span>&gt;</span> accounts) &#123;</span><br><span class="line">        this.accounts = accounts;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"something"</span> <span class="attr">class</span>=<span class="string">"x.y.SomeClass"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"accounts"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">map</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"one"</span> <span class="attr">value</span>=<span class="string">"9.99"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"two"</span> <span class="attr">value</span>=<span class="string">"2.75"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"six"</span> <span class="attr">value</span>=<span class="string">"3.99"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">map</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>当<code>something</code>的属性<code>accounts</code>准备注入的时候，accounts的泛型信息Map<code>Map&lt;String, Float&gt;</code> 就会通过反射拿到。 这样，Spring的类型转换系统能够识别不同的类型，如上面的例子<code>Float</code>然后会将字符串的值<code>9.99, 2.75</code>, 和<code>3.99</code>转换成对应的<code>Float</code>类型。</p>
<p><a id="beans-null-element"></a></p>
<h5 id="Null-and-空字符串"><a href="#Null-and-空字符串" class="headerlink" title="Null and 空字符串"></a><a href="#beans-null-element"></a>Null and 空字符串</h5><p><code>Strings</code>将属性的空参数视为空字符串。下面基于XML的元数据配置就会将<code>email</code> 属性配置为String的值。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"ExampleBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"email"</span> <span class="attr">value</span>=<span class="string">""</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>上面的示例等效于以下Java代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">exampleBean.setEmail(<span class="string">""</span>);</span><br></pre></td></tr></table></figure>

<p><code>&lt;null/&gt;</code>将被处理为null值。以下清单显示了一个示例:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"ExampleBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"email"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">null</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>上述配置等同于以下Java代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">exampleBean.setEmail(<span class="keyword">null</span>);</span><br></pre></td></tr></table></figure>

<p><a id="beans-p-namespace"></a></p>
<h5 id="使用p命名空间简化XML配置"><a href="#使用p命名空间简化XML配置" class="headerlink" title="使用p命名空间简化XML配置"></a><a href="#beans-p-namespace"></a>使用p命名空间简化XML配置</h5><p>p命名空间让开发者可以使用<code>bean</code>的属性，而不必使用嵌套的<code>&lt;property/&gt;</code>元素。</p>
<p>Spring是支持基于XML的格式化<a href="#xsd-schemas">命名空间</a>扩展的。本节讨论的<code>beans</code> 配置都是基于XML的，p命名空间是定义在Spring Core中的（不是在XSD文件）。</p>
<p>以下示例显示了两个XML片段（第一个使用标准XML格式，第二个使用p命名空间），它们解析为相同的结果：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:p</span>=<span class="string">"http://www.springframework.org/schema/p"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"classic"</span> <span class="attr">class</span>=<span class="string">"com.example.ExampleBean"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"email"</span> <span class="attr">value</span>=<span class="string">"someone@somewhere.com"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"p-namespace"</span> <span class="attr">class</span>=<span class="string">"com.example.ExampleBean"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">p:email</span>=<span class="string">"someone@somewhere.com"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>上面的例子在bean中定义了<code>email</code>的属性。这种定义告知Spring这是一个属性声明。如前面所描述的，p命名空间并没有标准的定义模式，所以开发者可以将属性的名称配置为依赖名称。</p>
<p>下一个示例包括另外两个bean定义，它们都引用了另一个bean:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:p</span>=<span class="string">"http://www.springframework.org/schema/p"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"john-classic"</span> <span class="attr">class</span>=<span class="string">"com.example.Person"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"name"</span> <span class="attr">value</span>=<span class="string">"John Doe"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"spouse"</span> <span class="attr">ref</span>=<span class="string">"jane"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"john-modern"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">"com.example.Person"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">p:name</span>=<span class="string">"John Doe"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">p:spouse-ref</span>=<span class="string">"jane"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"jane"</span> <span class="attr">class</span>=<span class="string">"com.example.Person"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"name"</span> <span class="attr">value</span>=<span class="string">"Jane Doe"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>此示例不仅包含使用p命名空间的属性值，还使用特殊格式来声明属性引用。第一个bean定义使用<code>&lt;property name=&quot;spouse&quot; ref=&quot;jane&quot;/&gt;</code>来创建从bean <code>john</code>到bean <code>jane</code>的引用， 而第二个bean定义使用<code>p:spouse-ref=&quot;jane&quot;</code>来作为指向bean的引用。在这个例子中 <code>spouse</code>是属性的名字，而<code>-ref</code>部分表名这个依赖不是直接的类型，而是引用另一个bean。</p>
<p>p命名空间并不如标准XML格式灵活。例如，声明属性的引用可能和一些以<code>Ref</code>结尾的属性相冲突，而标准的XML格式就不会。Spring团队推荐开发者能够和团队商量一下，协商使用哪一种方式，而不要同时使用三种方法。</p>
<p><a id="beans-c-namespace"></a></p>
<h5 id="使用c命名空间简化XML"><a href="#使用c命名空间简化XML" class="headerlink" title="使用c命名空间简化XML"></a><a href="#beans-c-namespace"></a>使用c命名空间简化XML</h5><p>与 <a href="#beans-p-namespace">p命名空间</a>类似，c命名空间是在Spring 3.1首次引入的，c命名空间允许使用内联的属性来配置构造参数而不必使用<code>constructor-arg</code> 。</p>
<p>以下示例使用<code>c:</code>命名空间的例子来执行与<a href="#beans-constructor-injection">基于Constructor的依赖注入</a>相同的操作：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:c</span>=<span class="string">"http://www.springframework.org/schema/c"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"thingOne"</span> <span class="attr">class</span>=<span class="string">"x.y.ThingTwo"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"thingTwo"</span> <span class="attr">class</span>=<span class="string">"x.y.ThingThree"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- traditional declaration --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"thingOne"</span> <span class="attr">class</span>=<span class="string">"x.y.ThingOne"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"thingTwo"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"thingThree"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">value</span>=<span class="string">"something@somewhere.com"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- c-namespace declaration --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"thingOne"</span> <span class="attr">class</span>=<span class="string">"x.y.ThingOne"</span> <span class="attr">c:thingTwo-ref</span>=<span class="string">"thingTwo"</span> <span class="attr">c:thingThree-ref</span>=<span class="string">"thingThree"</span> <span class="attr">c:email</span>=<span class="string">"something@somewhere.com"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>c:</code>:命名空间使用了和<code>p:</code> :命名空间相类似的方式（使用了<code>-ref</code> 来配置引用).而且,同样的,c命名空间也是定义在Spring Core中的（不是XSD模式).</p>
<p>在少数的例子之中,构造函数的参数名字并不可用（通常,如果字节码没有debug信息的编译),你可以使用回调参数的索引，如下面的例子:</p>
<pre><code>&lt;!-- c-namespace index declaration --&gt;
&lt;bean id=&quot;thingOne&quot; class=&quot;x.y.ThingOne&quot; c:_0-ref=&quot;thingTwo&quot; c:_1-ref=&quot;thingThree&quot;/&gt;</code></pre><p>由于XML语法，索引表示法需要使用<code>_</code>作为属性名字的前缀，因为XML属性名称不能以数字开头（即使某些IDE允许它）。</p>
<p>实际上，<a href="#beans-factory-ctor-arguments-resolution">构造函数解析机制</a>在匹配参数方面非常有效，因此除非您确实需要，否则我们建议在整个配置中使用名称表示法。</p>
<p><a id="beans-compound-property-names"></a></p>
<h5 id="组合属性名"><a href="#组合属性名" class="headerlink" title="组合属性名"></a><a href="#beans-compound-property-names"></a>组合属性名</h5><p>开发者可以配置混合的属性，只需所有的组件路径（除了最后一个属性名字）不能为<code>null</code>即可。参考如下定义：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"something"</span> <span class="attr">class</span>=<span class="string">"things.ThingOne"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"fred.bob.sammy"</span> <span class="attr">value</span>=<span class="string">"123"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>something</code>有 <code>fred</code>的属性，而其中<code>fred</code>属性有<code>bob</code>属性，而<code>bob</code>属性之中有<code>sammy</code>属性，那么最后这个<code>sammy</code>属性会配置为123。 想要上述的配置能够生效，<code>fred</code>属性需要有<code>bob</code>属性而且在<code>fred</code>构造之后不为null即可。</p>
<p><a id="beans-factory-dependson"></a></p>
<h4 id="1-4-3-使用-depends-on属性"><a href="#1-4-3-使用-depends-on属性" class="headerlink" title="1.4.3. 使用 depends-on属性"></a><a href="#beans-factory-dependson"></a>1.4.3. 使用 <code>depends-on</code>属性</h4><p>如果一个bean是另一个bean的依赖，通常这个bean也就是另一个bean的属性之一。多数情况下，开发者可以在配置XML元数据的时候使用<a href="#beans-ref-element"><code>&lt;ref/&gt;</code></a>标签。 然而，有时bean之间的依赖不是直接关联的。例如：需要调用类的静态实例化器来触发依赖，类似数据库驱动注册。<code>depends-on</code>属性可以显式强制初始化一个或多个bean。 以下示例使用depends-on属性表示对单个bean的依赖关系:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"beanOne"</span> <span class="attr">class</span>=<span class="string">"ExampleBean"</span> <span class="attr">depends-on</span>=<span class="string">"manager"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"manager"</span> <span class="attr">class</span>=<span class="string">"ManagerBean"</span> /&gt;</span></span><br></pre></td></tr></table></figure>

<p>如果想要依赖多个bean，可以提供多个名字作为<code>depends-on</code>的值。以逗号、空格或者分号分割:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"beanOne"</span> <span class="attr">class</span>=<span class="string">"ExampleBean"</span> <span class="attr">depends-on</span>=<span class="string">"manager,accountDao"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"manager"</span> <span class="attr">ref</span>=<span class="string">"manager"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"manager"</span> <span class="attr">class</span>=<span class="string">"ManagerBean"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"accountDao"</span> <span class="attr">class</span>=<span class="string">"x.y.jdbc.JdbcAccountDao"</span> /&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>depends-on</code>属性既可以指定初始化时间依赖性，也可以指定单独的bean，相应的销毁时间的依赖。独立定义了<code>depends-on</code>属性的bean会优先销毁 （相对于<code>depends-on</code>的bean销毁，这样<code>depends-on</code>可以控制销毁的顺序。</p>
<p><a id="beans-factory-lazy-init"></a></p>
<h4 id="1-4-4-懒加载Bean"><a href="#1-4-4-懒加载Bean" class="headerlink" title="1.4.4. 懒加载Bean"></a><a href="#beans-factory-lazy-init"></a>1.4.4. 懒加载Bean</h4><p>默认情况下， <code>ApplicationContext</code> 会在实例化的过程中创建和配置所有的单例<a href="#beans-factory-scopes-singleton">singleton</a> bean。总的来说， 这个预初始化是很不错的。因为这样能及时发现环境上的一些配置错误，而不是系统运行了很久之后才发现。如果这个行为不是迫切需要的，开发者可以通过将Bean标记为延迟加载就能阻止这个预初始化 懒加载bean会通知IoC不要让bean预初始化而是在被引用的时候才会实例化。</p>
<p>在XML中，此行为由<code>&lt;bean/&gt;</code>元素上的<code>lazy-init</code> 属性控制，如以下示例所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"lazy"</span> <span class="attr">class</span>=<span class="string">"com.something.ExpensiveToCreateBean"</span> <span class="attr">lazy-init</span>=<span class="string">"true"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"not.lazy"</span> <span class="attr">class</span>=<span class="string">"com.something.AnotherBean"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>当将bean配置为上述XML的时候， <code>ApplicationContext</code>之中的<code>lazy</code> bean是不会随着 <code>ApplicationContext</code>的启动而进入到预初始化状态的。 只有那些非延迟加载的bean是处于预初始化的状态的。</p>
<p>然而，如果延迟加载的类是作为单例非延迟加载的bean的依赖而存在的话，<code>ApplicationContext</code>仍然会在<code>ApplicationContext</code>启动的时候加载。 因为作为单例bean的依赖，会随着单例bean的实例化而实例化。</p>
<p>您还可以使用<code>&lt;beans/&gt;</code>元素上的<code>default-lazy-init</code>属性在容器级别控制延迟初始化，以下示例显示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">default-lazy-init</span>=<span class="string">"true"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- no beans will be pre-instantiated... --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><a id="beans-factory-autowire"></a></p>
<h4 id="1-4-5-自动装配"><a href="#1-4-5-自动装配" class="headerlink" title="1.4.5. 自动装配"></a><a href="#beans-factory-autowire"></a>1.4.5. 自动装配</h4><p>Spring容器可以根据bean之间的依赖关系自动装配，开发者可以让Spring通过<code>ApplicationContext</code>来自动解析这些关联，自动装载有很多优点:</p>
<ul>
<li><p>自动装载能够明显的减少指定的属性或者是构造参数。（在本章<a href="#beans-child-bean-definitions">其他地方讨论</a>的其他机制，如bean模板，在这方面也很有价值。）</p>
</li>
<li><p>自动装载可以扩展开发者的对象，比如说，如果开发者需要加一个依赖，只需关心如何更改配置即可自动满足依赖关联。这样，自动装载在开发过程中是极其高效的，无需明确选择装载的依赖会使系统更加稳定</p>
</li>
</ul>
<p>使用基于XML的配置元数据（请参阅<a href="#beans-factory-collaborators">依赖注入</a>）时，可以使用<code>&lt;bean/&gt;</code> 元素的<code>autowire</code>属性为bean定义指定autowire模式。 自动装配功能有四种方式。开发者可以指定每个bean的装配方式，这样bean就知道如何加载自己的依赖。下表描述了四种自动装配模式：</p>
<p>Table 2. 装配模式</p>
<table>
<thead>
<tr>
<th>模式</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td><code>no</code></td>
<td>(默认) 不自动装配。Bean引用必须由 <code>ref</code> 元素定义，对于比较大的项目的部署，不建议修改默认的配置 ，因为明确指定协作者可以提供更好的控制和清晰度。在某种程度上，它记录了系统的结构。</td>
</tr>
<tr>
<td><code>byName</code></td>
<td>按属性名称自动装配。 Spring查找与需要自动装配的属性同名的bean。 例如，如果bean配置为根据名字装配，他包含 的属性名字为<code>master</code>（即，它具有<code>setMaster(..)</code>方法），则Spring会查找名为 <code>master</code> 的bean定义并使用它来设置属性。</td>
</tr>
<tr>
<td><code>byType</code></td>
<td>如果需要自动装配的属性的类型在容器中只存在一个的话，他允许自动装配。如果存在多个，则抛出致命异常，这表示您不能对该bean使用<code>byType</code>自动装配。 如果没有匹配的bean，则不会发生任何事情（未设置该属性）。</td>
</tr>
<tr>
<td><code>constructor</code></td>
<td>类似于<code>byType</code>，但应用于构造函数参数。 如果容器中没有一个Bean的类型和构造函数参数类型一致的话，则会引发致命错误。</td>
</tr>
</tbody></table>
<p>通过<code>byType</code>或者<code>constructor</code>的自动装配方式，开发者可以装载数组和强类型集合。在这样的例子中，所有容器中的匹配了指定类型的bean都会自动装配到bean上来完成依赖注入。 开发者可以自动装配key为<code>String</code>.的强类型的 <code>Map</code> 。自动装配的Map值会包含所有的bean实例值来匹配指定的类型，<code>Map</code>的key会包含关联的bean的名字。</p>
<p><a id="beans-autowired-exceptions"></a></p>
<h5 id="自动装配的局限和缺点"><a href="#自动装配的局限和缺点" class="headerlink" title="自动装配的局限和缺点"></a><a href="#beans-autowired-exceptions"></a>自动装配的局限和缺点</h5><p>自动装配在项目中一致使用时效果最佳。如果一般不使用自动装配，那么开发人员使用它来装配一个或两个bean定义可能会让人感到困惑。</p>
<p>考虑自动装配的局限和缺点:</p>
<ul>
<li><p><code>property</code>和<code>constructor-arg</code>设置中的显式依赖项始终覆盖自动装配。开发者不能自动装配一些简单属性，您不能自动装配简单属性，例如基本类型 ，字符串和类（以及此类简单属性的数组）。这种限制是按设计的。</p>
</li>
<li><p>自动装配比显式的配置更容易歧义，尽管上表表明了不同自动配置的特点，Spring也会尽可能避免不必要的装配错误。但是Spring管理的对象关系仍然不如显式配置那样明确。</p>
</li>
<li><p>从Spring容器生成文档的工具可能无法有效的提供装配信息。</p>
</li>
<li><p>容器中的多个bean定义可能与setter方法或构造函数参数所指定的类型相匹配， 这有利于自动装配。对于arrays, collections, or <code>Map</code>实例来说这不是问题。但是如果是对只有一个依赖项的值是有歧义的话，那么这个项是无法解析的。如果没有唯一的bean，则会抛出异常。</p>
</li>
</ul>
<p>在后面的场景，你可有如下的选择：</p>
<ul>
<li>放弃自动装配，改用显式的配置。</li>
<li>通过将<code>autowire-candidate</code> 属性设置为<code>false</code>，避免对bean定义进行自动装配，<a href="#beans-factory-autowire-candidate">如下一节所述</a>。</li>
<li>通过将其<code>&lt;bean/&gt;</code> 元素的<code>primary</code>属性设置为 <code>true</code>，将单个bean定义指定为主要候选项。</li>
<li>使用基于注解的配置实现更细粒度的控制，如<a href="#beans-annotation-config">基于注解的容器配置</a>中所述。</li>
</ul>
<p><a id="beans-factory-autowire-candidate"></a></p>
<h5 id="将bean从自动装配中排除"><a href="#将bean从自动装配中排除" class="headerlink" title="将bean从自动装配中排除"></a><a href="#beans-factory-autowire-candidate"></a>将bean从自动装配中排除</h5><p>在每个bean的基础上，您可以从自动装配中排除bean。 在Spring的XML格式中，将<code>&lt;bean/&gt;</code> 元素的<code>autowire-candidate</code> 属性设置为<code>false</code>。 容器使特定的bean定义对自动装配基础结构不可用（包括注解样式配置，如<a href="#beans-autowired-annotation"><code>@Autowired</code></a>）。</p>
<p><code>autowire-candidate</code> 属性旨在仅影响基于类型的自动装配。 它不会影响名称的显式引用，即使指定的bean未标记为autowire候选，也会解析它。 因此，如果名称匹配，则按名称自动装配会注入bean。</p>
<p>开发者可以通过模式匹配而不是Bean的名字来限制自动装配的候选者。最上层的<code>&lt;beans/&gt;</code> 元素会在<code>default-autowire-candidates</code> 属性中来配置多种模式。 例如，限制自动装配候选者的名字以<code>Repository</code>结尾，可以配置成<code>*Repository</code>。如果需要配置多种模式，只需要用逗号分隔开即可。 bean定义的<code>autowire-candidate</code>属性的显式值<code>true</code> 或<code>false</code>始终优先。 对于此类bean，模式匹配规则不适用。</p>
<p>上面的这些技术在配置那些无需自动装配的bean是相当有效的，当然这并不是说这类bean本身无法自动装配其他的bean。而是说这些bean不再作为自动装配的依赖候选者。</p>
<p><a id="beans-factory-method-injection"></a></p>
<h4 id="1-4-6-方法注入"><a href="#1-4-6-方法注入" class="headerlink" title="1.4.6.方法注入"></a><a href="#beans-factory-method-injection"></a>1.4.6.方法注入</h4><p>在大多数的应用场景下，多数的bean都是<a href="#beans-factory-scopes-singleton">单例</a>的。当这个单例的bean需要和另一个单例的或者非单例的bean协作使用的时候，开发者只需要配置依赖bean为这个bean的属性即可。 但是有时会因为bean具有不同的生命周期而产生问题。假设单例的bean A在每个方法调用中使用了非单例的bean B。容器只会创建bean A一次，而只有一个机会来配置属性。 那么容器就无法为每一次创建bean A时都提供新的bean B实例。</p>
<p>一种解决方案就是放弃IoC，开发者可以通过实现<code>ApplicationContextAware</code>接口让<a href="#beans-factory-aware">bean A对ApplicationContext</a>可见。 从而通过调用<a href="#beans-factory-client"><code>getBean(&quot;B&quot;)</code></a>来在bean A 需要新的实例的时候来获取到新的B实例。参考下面例子。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// a class that uses a stateful Command-style class to perform some processing</span></span><br><span class="line"><span class="keyword">package</span> fiona.apple;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Spring-API imports</span></span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.BeansException;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.ApplicationContext;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.ApplicationContextAware;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CommandManager</span> <span class="keyword">implements</span> <span class="title">ApplicationContextAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> ApplicationContext applicationContext;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">process</span><span class="params">(Map commandState)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// grab a new instance of the appropriate Command</span></span><br><span class="line">        Command command = createCommand();</span><br><span class="line">        <span class="comment">// set the state on the (hopefully brand new) Command instance</span></span><br><span class="line">        command.setState(commandState);</span><br><span class="line">        <span class="keyword">return</span> command.execute();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Command <span class="title">createCommand</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// notice the Spring API dependency!</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.applicationContext.getBean(<span class="string">"command"</span>, Command<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            ApplicationContext applicationContext)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.applicationContext = applicationContext;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的代码并不让人十分满意，因为业务的代码已经与Spring框架耦合在一起。方法注入是Spring IoC容器的一个高级功能，可以让您处理这种问题。 Spring提供了一个稍微高级的注入方式来处理这种问题</p>
<p>您可以在此<a href="https://spring.io/blog/2004/08/06/method-injection/" target="_blank" rel="noopener">博客条目</a>中阅读有关方法注入的更多信息。</p>
<p><a id="beans-factory-lookup-method-injection"></a></p>
<h5 id="查找方法注入"><a href="#查找方法注入" class="headerlink" title="查找方法注入"></a><a href="#beans-factory-lookup-method-injection"></a>查找方法注入</h5><p>查找方法注入是容器覆盖管理bean上的方法的能力，以便返回容器中另一个命名bean的查找结果。查找方法通常涉及原型bean，<a href="#beans-factory-method-injection">如前面描述的场景</a>。 Spring框架通过使用CGLIB库生成的字节码来生成动态子类重写的方法实现此注入。</p>
<ul>
<li><p>如果想让这个动态子类正常工作，那么Spring容器所继承的Bean不能是<code>final</code>的，而覆盖的方法也不能是<code>final</code>的。</p>
</li>
<li><p>对具有<code>抽象</code>方法的类进行单元测试时，需要开发者对类进行子类化，并提供<code>抽象</code>方法的具体实现。</p>
</li>
<li><p>组件扫描也需要具体的方法，因为它需要获取具体的类。</p>
</li>
<li><p>另一个关键限制是查找方法不适用于工厂方法，特别是在配置类中不使用<code>@Bean</code>的方法。因为在这种情况下，容器不负责创建实例，因此不能在运行时创建运行时生成的子类。</p>
</li>
</ul>
<p>对于前面代码片段中的<code>CommandManager</code>类，Spring容器动态地覆盖<code>createCommand()</code>方法的实现。 <code>CommandManager</code>类不再拥有任何的Spring依赖，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> fiona.apple;</span><br><span class="line"></span><br><span class="line"><span class="comment">// no more Spring imports!</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">CommandManager</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">process</span><span class="params">(Object commandState)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// grab a new instance of the appropriate Command interface</span></span><br><span class="line">        Command command = createCommand();</span><br><span class="line">        <span class="comment">// set the state on the (hopefully brand new) Command instance</span></span><br><span class="line">        command.setState(commandState);</span><br><span class="line">        <span class="keyword">return</span> command.execute();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// okay... but where is the implementation of this method?</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> Command <span class="title">createCommand</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在包含需要注入方法的客户端类中 (在本例中为<code>CommandManager</code>）注入方法的签名需要如下形式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;public|protected&gt; [abstract] &lt;return-type&gt; theMethodName(no-arguments);</span><br></pre></td></tr></table></figure>

<p>如果方法是<code>abstract</code>的， 那么动态生成的子类会实现该方法。否则，动态生成的子类将覆盖原始类定义的具体方法。例如：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- a stateful bean deployed as a prototype (non-singleton) --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"myCommand"</span> <span class="attr">class</span>=<span class="string">"fiona.apple.AsyncCommand"</span> <span class="attr">scope</span>=<span class="string">"prototype"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- inject dependencies here as required --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- commandProcessor uses statefulCommandHelper --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"commandManager"</span> <span class="attr">class</span>=<span class="string">"fiona.apple.CommandManager"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">lookup-method</span> <span class="attr">name</span>=<span class="string">"createCommand"</span> <span class="attr">bean</span>=<span class="string">"myCommand"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>当需要新的myCommand bean实例时，标识为<code>commandManager</code>的bean会调用自身的<code>createCommand()</code>方法.开发者必须小心部署<code>myCommand</code> bean为原型bean. 如果所需的bean是<a href="#beans-factory-scopes-singleton">单例</a>的,那么每次都会返回相同的<code>myCommand</code> bean实例.</p>
<p>另外,如果是基于注解的配置模式,你可以在查找方法上定义<code>@Lookup</code>注解,如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">CommandManager</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">process</span><span class="params">(Object commandState)</span> </span>&#123;</span><br><span class="line">        Command command = createCommand();</span><br><span class="line">        command.setState(commandState);</span><br><span class="line">        <span class="keyword">return</span> command.execute();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Lookup</span>(<span class="string">"myCommand"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> Command <span class="title">createCommand</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>或者，更常见的是，开发者也可以根据查找方法的返回类型来查找匹配的bean，如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">CommandManager</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">process</span><span class="params">(Object commandState)</span> </span>&#123;</span><br><span class="line">        MyCommand command = createCommand();</span><br><span class="line">        command.setState(commandState);</span><br><span class="line">        <span class="keyword">return</span> command.execute();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Lookup</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> MyCommand <span class="title">createCommand</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意开发者可以通过创建子类实现lookup方法，以便使它们与Spring的组件扫描规则兼容，同时抽象类会在默认情况下被忽略。这种限制不适用于显式注册bean或明确导入bean的情况。</p>
<p>另一种可以访问不同生命周期的方法是<code>ObjectFactory</code>/<code>Provider</code>注入，具体参看 <a href="#beans-factory-scopes-other-injection">作用域的bean依赖</a></p>
<p>您可能还会发现<code>ServiceLocatorFactoryBean</code>（在<code>org.springframework.beans.factory.config</code>包中）很有用。</p>
<p><a id="beans-factory-arbitrary-method-replacement"></a></p>
<h5 id="替换任意方法"><a href="#替换任意方法" class="headerlink" title="替换任意方法"></a><a href="#beans-factory-arbitrary-method-replacement"></a>替换任意方法</h5><p>从前面的描述中，我们知道查找方法是有能力来覆盖任何由容器管理的bean方法的。开发者最好跳过这一部分，除非一定需要用到这个功能。</p>
<p>通过基于XML的元数据配置，开发者可以使用<code>replaced-method</code>元素来替换已存在方法的实现。考虑以下类，它有一个我们想要覆盖的名为<code>computeValue</code> 的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyValueCalculator</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">computeValue</span><span class="params">(String input)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// some real code...</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// some other methods...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现<code>org.springframework.beans.factory.support.MethodReplacer</code>接口的类提供了新的方法定义，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * meant to be used to override the existing computeValue(String)</span></span><br><span class="line"><span class="comment"> * implementation in MyValueCalculator</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ReplacementComputeValue</span> <span class="keyword">implements</span> <span class="title">MethodReplacer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">reimplement</span><span class="params">(Object o, Method m, Object[] args)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="comment">// get the input value, work with it, and return a computed result</span></span><br><span class="line">        String input = (String) args[<span class="number">0</span>];</span><br><span class="line">        ...</span><br><span class="line">        <span class="keyword">return</span> ...;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果需要覆盖bean方法的XML配置如下类似于以下示例：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"myValueCalculator"</span> <span class="attr">class</span>=<span class="string">"x.y.z.MyValueCalculator"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- arbitrary method replacement --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">replaced-method</span> <span class="attr">name</span>=<span class="string">"computeValue"</span> <span class="attr">replacer</span>=<span class="string">"replacementComputeValue"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">arg-type</span>&gt;</span>String<span class="tag">&lt;/<span class="name">arg-type</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">replaced-method</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"replacementComputeValue"</span> <span class="attr">class</span>=<span class="string">"a.b.c.ReplacementComputeValue"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>您可以在<code>&lt;replaced-method/&gt;</code>元素中使用一个或多个 <code>&lt;arg-type/&gt;</code>元素来指示被覆盖的方法的方法。当需要覆盖的方法存在重载方法时，必须指定所需参数。 为了方便起见，字符串的类型会匹配以下类型，它完全等同于<code>java.lang.String</code></p>
<pre><code>java.lang.String
String
Str</code></pre><p>因为，通常来说参数的个数已经足够区别不同的方法，这种快捷的写法可以省去很多的代码。</p>
<p><a id="beans-factory-scopes"></a></p>
<h3 id="1-5-bean的作用域"><a href="#1-5-bean的作用域" class="headerlink" title="1.5. bean的作用域"></a><a href="#beans-factory-scopes"></a>1.5. bean的作用域</h3><p>创建bean定义时，同时也会定义该如何创建Bean实例。 这些具体创建的过程是很重要的，因为只有通过对这些配置过程，您才能创建实例对象。</p>
<p>您不仅可以将不同的依赖注入到bean中，还可以配置bean的作用域。这种方法是非常强大而且也非常灵活，开发者可以通过配置来指定对象的作用域，无需在Java类的层次上配置。 bean可以配置多种作用域，Spring框架支持五种作用域，有三种作用域是当开发者使用基于Web的<code>ApplicationContext</code>的时候才有效的。您还可以创建<a href="#beans-factory-scopes-custom">自定义范围.</a>。</p>
<p>下表描述了支持的范围:</p>
<p>Table 3. Bean 的作用域</p>
<table>
<thead>
<tr>
<th>作用域</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><a href="#beans-factory-scopes-singleton">singleton</a></td>
<td>(默认) 每一Spring IOC容器都拥有唯一的实例对象。</td>
</tr>
<tr>
<td><a href="#beans-factory-scopes-prototype">prototype</a></td>
<td>一个Bean定义可以创建任意多个实例对象.</td>
</tr>
<tr>
<td><a href="#beans-factory-scopes-request">request</a></td>
<td>将单个bean定义范围限定为单个HTTP请求的生命周期。 也就是说，每个HTTP请求都有自己的bean实例，它是在单个bean定义的后面创建的。 只有基于Web的Spring <code>ApplicationContext</code>的才可用。</td>
</tr>
<tr>
<td><a href="#beans-factory-scopes-session">session</a></td>
<td>将单个bean定义范围限定为HTTP <code>Session</code>的生命周期。 只有基于Web的Spring <code>ApplicationContext</code>的才可用。</td>
</tr>
<tr>
<td><a href="#beans-factory-scopes-application">application</a></td>
<td>将单个bean定义范围限定为<code>ServletContext</code>的生命周期。 只有基于Web的Spring <code>ApplicationContext</code>的才可用。</td>
</tr>
<tr>
<td><a href="https://github.com/DocsHome/spring-docs/blob/master/pages/web/web.md#websocket-stomp-websocket-scope" target="_blank" rel="noopener">websocket</a></td>
<td>将单个bean定义范围限定为 <code>WebSocket</code>的生命周期。 只有基于Web的Spring <code>ApplicationContext</code>的才可用。</td>
</tr>
</tbody></table>
<p>从Spring 3.0开始，线程作用域默认是可用的，但默认情况下未注册。 有关更多信息，请参阅<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/support/SimpleThreadScope.html" target="_blank" rel="noopener"><code>SimpleThreadScope</code></a>的文档。 有关如何注册此范围或任何其他自定义范围的说明，请参阅使用<a href="#beans-factory-scopes-custom-using">自定义范围</a>。</p>
<p><a id="beans-factory-scopes-singleton"></a></p>
<h4 id="1-5-1-单例作用域"><a href="#1-5-1-单例作用域" class="headerlink" title="1.5.1. 单例作用域"></a><a href="#beans-factory-scopes-singleton"></a>1.5.1. 单例作用域</h4><p>单例bean在全局只有一个共享的实例，所有依赖单例bean的场景中，容器返回的都是同一个实例。</p>
<p>换句话说，当您定义一个bean并且它的范围是一个单例时，Spring IoC容器只会根据bean的定义来创建该bean的唯一实例。 这些唯一的实例会缓存到容器中，后续针对单例bean的请求和引用，都会从这个缓存中拿到这个唯一实例。 下图显示了单例范围的工作原理：</p>
<p><img src="https://github.com/DocsHome/spring-docs/blob/master/pages/images/singleton.png" alt="singleton"></p>
<p>Spring的单例bean概念不同于设计模式（GoF）之中所定义的单例模式。设计模式中的单例模式是将一个对象的作用域硬编码的，一个ClassLoader只能有唯一的一个实例。 而Spring的单例作用域是以容器为前提的，每个容器每个bean只能有一个实例。 这意味着，如果在单个Spring容器中为特定类定义一个bean，则Spring容器会根据bean定义创建唯一的bean实例。 单例作用域是Spring的默认作用域。 下面的例子是在XML中配置单例模式Bean的例子：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"accountService"</span> <span class="attr">class</span>=<span class="string">"com.something.DefaultAccountService"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- the following is equivalent, though redundant (singleton scope is the default) --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"accountService"</span> <span class="attr">class</span>=<span class="string">"com.something.DefaultAccountService"</span> <span class="attr">scope</span>=<span class="string">"singleton"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p><a id="beans-factory-scopes-prototype"></a></p>
<h4 id="1-5-2-原型作用域"><a href="#1-5-2-原型作用域" class="headerlink" title="1.5.2. 原型作用域"></a><a href="#beans-factory-scopes-prototype"></a>1.5.2. 原型作用域</h4><p>非单例的、原型bean指的是每次请求bean实例时,返回的都是新的对象实例。也就是说，每次注入到另外的bean或者通过调用 <code>getBean()</code>方法来获得的bean都是全新的实例。 基于线程安全性的考虑，当bean对象有状态时使用原型作用域，而无状态时则使用单例作用域。</p>
<p>下图说明了Spring原型作用域：:</p>
<p><img src="https://github.com/DocsHome/spring-docs/blob/master/pages/images/prototype.png" alt="prototype"></p>
<p>（数据访问对象（DAO）通常不配置为原型，因为典型的DAO不具有任何会话状态。我们可以更容易重用单例图的核心。）</p>
<p>用下面的例子来说明Spring的原型作用域:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"accountService"</span> <span class="attr">class</span>=<span class="string">"com.something.DefaultAccountService"</span> <span class="attr">scope</span>=<span class="string">"prototype"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>与其他作用域相比，Spring不会完整地管理原型bean的生命周期。 Spring容器只会初始化、配置和装载这些bean，然后传递给Client。但是之后就不会再有该原型实例的进一步记录。 也就是说，初始化生命周期回调方法在所有作用域的bean是都会调用的，但是销毁生命周期回调方法在原型bean是不会调用的。所以，客户端代码必须注意清理原型bean以及释放原型bean所持有的资源。 可以通过使用自定义的<a href="#beans-factory-extension-bpp">bean post-processor</a>（Bean的后置处理器）来让Spring释放掉原型bean所持有的资源。</p>
<p>在某些方面，Spring容器关于原型作用域的bean就是取代了Java的<code>new</code> 操作符。 所有的生命周期的控制都由客户端来处理（有关Spring容器中bean的生命周期的详细信息，请参阅<a href="#beans-factory-lifecycle">Bean的生命周期</a>）。</p>
<p><a id="beans-factory-scopes-sing-prot-interaction"></a></p>
<h4 id="1-5-3-依赖原型bean的单例bean"><a href="#1-5-3-依赖原型bean的单例bean" class="headerlink" title="1.5.3. 依赖原型bean的单例bean"></a><a href="#beans-factory-scopes-sing-prot-interaction"></a>1.5.3. 依赖原型bean的单例bean</h4><p>当您使用具有依赖于原型bean的单例作用域bean时，请注意在实例化时解析依赖项。 因此，如果将原型bean注入到单例的bean中，则会实例化一个新的原型bean，然后将依赖注入到单例bean中。 这个依赖的原型bean仍然是同一个实例。</p>
<p>但是，假设您希望单例作用域的bean在运行时重复获取原型作用域的bean的新实例。 您不能将原型作用域的bean依赖注入到您的单例bean中， 因为当Spring容器实例化单例bean并解析注入其依赖项时，该注入只发生一次。 如果您需要在运行时多次使用原型bean的新实例，请参阅<a href="#beans-factory-method-injection">方法注入</a>。</p>
<p><a id="beans-factory-scopes-other"></a></p>
<h4 id="1-5-4-请求，会话，应用程序和WebSocket作用域"><a href="#1-5-4-请求，会话，应用程序和WebSocket作用域" class="headerlink" title="1.5.4. 请求，会话，应用程序和WebSocket作用域"></a><a href="#beans-factory-scopes-other"></a>1.5.4. 请求，会话，应用程序和WebSocket作用域</h4><p><code>request</code>, <code>session</code>, <code>application</code>, 和 <code>websocket</code>作用域只有在Web中使用Spring的<code>ApplicationContext</code>（例如<code>ClassPathXmlApplicationContext</code>）的情况下才用得上。 如果在普通的Spring IoC容器，例如ClassPathXmlApplicationContext中使用这些作用域，将会抛出IllegalStateException异常来说明使用了未知的作用域。</p>
<p><a id="beans-factory-scopes-other-web-configuration"></a></p>
<h5 id="初始化Web的配置"><a href="#初始化Web的配置" class="headerlink" title="初始化Web的配置"></a><a href="#beans-factory-scopes-other-web-configuration"></a>初始化Web的配置</h5><p>为了能够使用请求 <code>request</code>, <code>session</code>, <code>application</code>, 和<code>websocket</code>（Web范围的bean），需要在配置bean之前作一些基础配置。 而对于标准的作用域，例如单例和原型作用域，这种基础配置是不需要的。</p>
<p>如何完成此初始设置取决于您的特定Servlet环境.</p>
<p>例如，如果开发者使用了Spring Web MVC框架，那么每一个请求都会通过Spring的<code>DispatcherServlet</code>来处理，那么也无需特殊的设置了。DispatcherServlet和DispatcherPortlet已经包含了相应状态。</p>
<p>如果您使用Servlet 2.5 Web容器，并且在Spring的<code>DispatcherServlet</code>之外处理请求（例如，使用JSF或Struts时），则需要注册<code>org.springframework.web.context.request.RequestContextListener</code>或者<code>ServletRequestListener</code>。 对于Servlet 3.0+，可以使用<code>WebApplicationInitializer</code>接口以编程方式完成此操作。 如果需要兼容旧版本容器的话，将以下声明添加到Web应用程序的<code>web.xml</code> 文件中:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">web-app</span>&gt;</span></span><br><span class="line">    ...</span><br><span class="line">    <span class="tag">&lt;<span class="name">listener</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">listener-class</span>&gt;</span></span><br><span class="line">            org.springframework.web.context.request.RequestContextListener</span><br><span class="line">        <span class="tag">&lt;/<span class="name">listener-class</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">listener</span>&gt;</span></span><br><span class="line">    ...</span><br><span class="line"><span class="tag">&lt;/<span class="name">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>或者，如果对Listener不是很熟悉，请考虑使用Spring的<code>RequestContextFilter</code>。 Filter映射取决于Web应用的配置，因此您必须根据需要进行更改。 以下清单显示了Web应用程序的过滤器部分:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">web-app</span>&gt;</span></span><br><span class="line">    ...</span><br><span class="line">    <span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>requestContextFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>org.springframework.web.filter.RequestContextFilter<span class="tag">&lt;/<span class="name">filter-class</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>requestContextFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">    ...</span><br><span class="line"><span class="tag">&lt;/<span class="name">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>DispatcherServlet</code>, <code>RequestContextListener</code>, and <code>RequestContextFilter</code>所做的工作实际上是一样的，都是将request对象请求绑定到服务的 <code>Thread</code>上。 这才使bean在之后的调用链上对请求和会话作用域可见。</p>
<p><a id="beans-factory-scopes-request"></a></p>
<h5 id="Request作用域"><a href="#Request作用域" class="headerlink" title="Request作用域"></a><a href="#beans-factory-scopes-request"></a>Request作用域</h5><p>参考下面这个XML配置的bean定义:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"loginAction"</span> <span class="attr">class</span>=<span class="string">"com.something.LoginAction"</span> <span class="attr">scope</span>=<span class="string">"request"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>Spring容器会在每次使用<code>LoginAction</code>来处理每个HTTP请求时都会创建新的<code>LoginAction</code>实例。也就是说，<code>LoginAction</code> bean的作用域是HTTP Request级别的。 开发者可以随意改变实例的状态，因为其他通过<code>loginAction</code>请求来创建的实例根本看不到开发者改变的实例状态，所有创建的Bean实例都是根据独立的请求创建的。当请求处理完毕，这个bean也将会销毁。</p>
<p>当使用注解配置或Java配置时，使用<code>@RequestScope</code>注解修饰的bean会被设置成request作用域。 以下示例显示了如何执行此操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestScope</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LoginAction</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-factory-scopes-session"></a></p>
<h5 id="Session作用域"><a href="#Session作用域" class="headerlink" title="Session作用域"></a><a href="#beans-factory-scopes-session"></a>Session作用域</h5><p>参考下面XML配置的bean的定义:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userPreferences"</span> <span class="attr">class</span>=<span class="string">"com.something.UserPreferences"</span> <span class="attr">scope</span>=<span class="string">"session"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>Spring容器通过在单个HTTP会话的生命周期中使用<code>UserPreferences</code> bean定义来创建<code>UserPreferences</code> bean的新实例。换言之，<code>UserPreferences</code> Bean的作用域是HTTP S<code>Session</code>级别的，在request-scoped作用域的bean上， 开发者可以随意的更改实例的状态，同样，其他HTTP <code>Session</code>的基本实例在每个<code>Session</code>中都会请求userPreferences来创建新的实例，所以，开发者更改bean的状态， 对于其他的Bean仍然是不可见的。当HTTP <code>Session</code>被销毁时，根据这个<code>Session</code>来创建的bean也将会被销毁。</p>
<p>使用注解配置和Java配置时，使用<code>@SessionScope</code> 注解修饰的 bean 会被设置成<code>session</code>作用域。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SessionScope</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserPreferences</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-factory-scopes-application"></a></p>
<h5 id="Application作用域"><a href="#Application作用域" class="headerlink" title="Application作用域"></a><a href="#beans-factory-scopes-application"></a>Application作用域</h5><p>参考下面用XML配置的bean的定义:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"appPreferences"</span> <span class="attr">class</span>=<span class="string">"com.something.AppPreferences"</span> <span class="attr">scope</span>=<span class="string">"application"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>Spring容器会在整个Web应用内使用到<code>appPreferences</code>的时候创建一个新的<code>AppPreferences</code>的实例。也就是说，<code>appPreferences</code> bean是在<code>ServletContext</code> 级别的， 就像普通的<code>ServletContext</code> 属性一样。这种作用域在一些程度上来说和Spring的单例作用域是极为相似，但是也有如下不同之处，应用作用域是每个<code>ServletContext</code> 中包含一个 而不是每个Spring ApplicationContext中只有一个（某些应用可能包含多个ApplicationContext）。应用作用域仅仅对<code>ServletContext</code> 可见，单例bean是对ApplicationContext可见。</p>
<p>当使用注解配置或Java配置时，使用<code>@ApplicationScope</code> 注解修饰的bean会被设置成<code>application</code>作用域 。以下示例显示了如何执行此操作:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ApplicationScope</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppPreferences</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-factory-scopes-other-injection"></a></p>
<h5 id="有作用域bean的依赖"><a href="#有作用域bean的依赖" class="headerlink" title="有作用域bean的依赖"></a><a href="#beans-factory-scopes-other-injection"></a>有作用域bean的依赖</h5><p>Spring IoC容器不仅仅管理对象（bean）的实例化，同时也负责装配依赖。如果开发者要将一个bean装配到比它作用域更广的bean时（例如HTTP请求返回的bean），那么开发者应当选择注入AOP代理而不是使用带作用域的bean。 也就是说，开发者需要注入代理对象，而这个代理对象既可以找到实际的bean，还能够创建全新的bean。</p>
<p>您还可以在作为单例的作用域的bean之间使用<code>&lt;aop:scoped-proxy/&gt;</code>，然后引用通过可序列化的中间代理，从而能够在反序列化时重新获取目标<code>单例</code>bean。</p>
<p>当针对原型作用域的bean声明<code>&lt;aop:scoped-proxy/&gt;</code>时，每个通过代理的调用都会产生新的目标实例。</p>
<p>此外，作用域代理并不是取得作用域bean的唯一安全方式。 开发者也可以通过简单的声明注入（即构造函数或setter参数或自动装配字段）<code>ObjectFactory&lt;MyTargetBean&gt;</code>， 然后允许通过类似<code>getObject()</code>的方法调用来获取一些指定的依赖，而不是直接储存依赖的实例。</p>
<p>作为扩展变体，您可以声明<code>ObjectProvider&lt;MyTargetBean&gt;</code>，它提供了几个额外的访问变体，包括<code>getIfAvailable</code> 和 <code>getIfUnique</code>。</p>
<p>JSR-330将这样的变种称为Provider，它使用<code>Provider&lt;MyTargetBean&gt;</code> 声明以及相关的 <code>get()</code> 方法来尝试获取每一个配置。 有关JSR-330整体的更多详细信息，<a href="#beans-standard-annotations">请参看此处</a>。</p>
<p>以下示例中的配置只有一行，但了解“为什么”以及它背后的“如何”非常重要：:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:aop</span>=<span class="string">"http://www.springframework.org/schema/aop"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/aop</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/aop/spring-aop.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- an HTTP Session-scoped bean exposed as a proxy --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userPreferences"</span> <span class="attr">class</span>=<span class="string">"com.something.UserPreferences"</span> <span class="attr">scope</span>=<span class="string">"session"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- instructs the container to proxy the surrounding bean --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">aop:scoped-proxy</span>/&gt;</span> (1)</span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- a singleton-scoped bean injected with a proxy to the above bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userService"</span> <span class="attr">class</span>=<span class="string">"com.something.SimpleUserService"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- a reference to the proxied userPreferences bean --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"userPreferences"</span> <span class="attr">ref</span>=<span class="string">"userPreferences"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>1</strong>、定义代理的行。</p>
<p>要创建这样的一个代理，只需要在带作用域的bean定义中添加子节点<code>&lt;aop:scoped-proxy/&gt;</code>即可（具体查看<a href="#beans-factory-scopes-other-injection-proxies">选择创建代理的类型</a>和 <a href="#xsd-schemas">基于XML Schema的配置</a>）。为什么在<code>request</code>, <code>session</code>和自定义作用域级别范围内的bean定义需要<code>&lt;aop:scoped-proxy/&gt;</code>， 考虑以下单例bean定义，并将其与您需要为上述范围定义的内容进行对比（请注意，以下<code>userPreferences</code>bean定义不完整）:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userPreferences"</span> <span class="attr">class</span>=<span class="string">"com.something.UserPreferences"</span> <span class="attr">scope</span>=<span class="string">"session"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userManager"</span> <span class="attr">class</span>=<span class="string">"com.something.UserManager"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"userPreferences"</span> <span class="attr">ref</span>=<span class="string">"userPreferences"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在上面的例子中，单例bean（<code>userManager</code>）注入了注入了HTTP <code>Session</code>级别的<code>userPreferences</code>依赖。 显然， 问题就是<code>userPreferences</code>在Spring容器中只会实例化一次。它的依赖项（在这种情况下只有一个，<code>userPreferences</code>）也只注入一次。 这意味着<code>userManager</code> 每次使用的是完全相同的<code>userPreferences</code>对象（即最初注入它的对象）进行操作。</p>
<p>这不是将短周期作用域bean注入到长周期作用域bean时所需的行为，例如将HTTP <code>Session</code>级别的作用域bean作为依赖注入到单例bean中。相反，开发者需要一个 <code>userManager</code>对象， 而在HTTP <code>Session</code>的生命周期中，开发者需要一个特定于HTTP Session的 userPreferences 对象。因此，容器创建一个对象，该对象公开与UserPreferences类（理想情况下为<code>UserPreferences</code>实例的对象） 完全相同的公共接口，该对象可以从作用域机制（HTTP Request、<code>Session</code>等）中获取真实的<code>UserPreferences</code>对象。容器将这个代理对象注入到<code>userManager</code>中， 而不知道这个<code>UserPreferences</code>引用是一个代理。在这个例子中，当一个UserManager实例在依赖注入的UserPreferences对象上调用一个方法时， 它实际上是在调用代理的方法，再由代理从HTTP <code>Session</code>（本例）获取真实的<code>UserPreferences</code>对象，并将方法调用委托给检索到的实际<code>UserPreferences</code>对象。</p>
<p>因此，在将<code>request-</code> and <code>session-scoped</code>的bean来作为依赖时，您需要以下（正确和完整）配置，如以下示例所示： 所以当开发者希望能够正确的使用配置请求、会话或者全局会话级别的bean来作为依赖时，需要进行如下类似的配置。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userPreferences"</span> <span class="attr">class</span>=<span class="string">"com.something.UserPreferences"</span> <span class="attr">scope</span>=<span class="string">"session"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">aop:scoped-proxy</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userManager"</span> <span class="attr">class</span>=<span class="string">"com.something.UserManager"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"userPreferences"</span> <span class="attr">ref</span>=<span class="string">"userPreferences"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><a id="beans-factory-scopes-other-injection-proxies"></a></p>
<h6 id="选择要创建的代理类型"><a href="#选择要创建的代理类型" class="headerlink" title="选择要创建的代理类型"></a><a href="#beans-factory-scopes-other-injection-proxies"></a>选择要创建的代理类型</h6><p>默认情况下，当Spring容器为使用<code>&lt;aop:scoped-proxy/&gt;</code> 元素标记的bean创建代理时，将创建基于CGLIB的类代理。</p>
<p>CGLIB代理只拦截公共方法调用！ 不要在这样的代理上调用非公共方法。 它们不会委托给实际的作用域目标对象。</p>
<p>或者，您可以通过为<code>&lt;aop:scoped-proxy/&gt;</code>元素的<code>proxy-target-class</code> 属性的值指定<code>false</code>来配置Spring容器， 以便为此类作用域bean创建基于JDK接口的标准代理。 使用基于接口的JDK代理意味着开发者无需引入第三方库即可完成代理。 但是，这也意味着带作用域的bean需要额外实现一个接口，而依赖是从这些接口来获取的。 以下示例显示基于接口的代理：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- DefaultUserPreferences implements the UserPreferences interface --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userPreferences"</span> <span class="attr">class</span>=<span class="string">"com.stuff.DefaultUserPreferences"</span> <span class="attr">scope</span>=<span class="string">"session"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">aop:scoped-proxy</span> <span class="attr">proxy-target-class</span>=<span class="string">"false"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"userManager"</span> <span class="attr">class</span>=<span class="string">"com.stuff.UserManager"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"userPreferences"</span> <span class="attr">ref</span>=<span class="string">"userPreferences"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>有关选择基于类或基于接口的代理的更多详细信息，请参阅<a href="#aop-proxying">代理机制</a>。</p>
<p><a id="beans-factory-scopes-custom"></a></p>
<h4 id="1-5-5-自定义作用域"><a href="#1-5-5-自定义作用域" class="headerlink" title="1.5.5. 自定义作用域"></a><a href="#beans-factory-scopes-custom"></a>1.5.5. 自定义作用域</h4><p>bean的作用域机制是可扩展的，开发者可以自定义作用域，甚至重新定义已经存在的作用域，但是Spring团队不推荐这样做，而且开发者也不能重写<code>singleton</code> 和 <code>prototype</code>作用域。</p>
<p><a id="beans-factory-scopes-custom-creating"></a></p>
<h5 id="创建自定义作用域"><a href="#创建自定义作用域" class="headerlink" title="创建自定义作用域"></a><a href="#beans-factory-scopes-custom-creating"></a>创建自定义作用域</h5><p>为了能够使Spring可以管理开发者定义的作用域，开发者需要实现<code>org.springframework.beans.factory.config.Scope</code>。如何实现自定义的作用域， 可以参考Spring框架的一些实现或者有关<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/config/Scope.html" target="_blank" rel="noopener"><code>Scope</code></a> 的javadoc</p>
<p><code>Scope</code>接口有四个方法用于操作对象,例如获取、移除或销毁等操作。</p>
<p>例如，传入Session作用域该方法将会返回一个 session-scoped的bean（如果它不存在，那么将会返回绑定session作用域的新实例）。下面的方法返回相应作用域的对象：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">Object <span class="title">get</span><span class="params">(String name, ObjectFactory objectFactory)</span></span></span><br></pre></td></tr></table></figure>

<p>下面的方法将从相应的作用域中移除对象。同样，以会话为例，该函数会删除会话作用域的Bean。删除的对象会作为返回值返回，当无法找到对象时将返回null。 以下方法从相应作用域中删除对象：:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">Object <span class="title">remove</span><span class="params">(String name)</span></span></span><br></pre></td></tr></table></figure>

<p>以下方法注册范围在销毁时或在Scope中的指定对象被销毁时应该执行的回调:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">registerDestructionCallback</span><span class="params">(String name, Runnable destructionCallback)</span></span></span><br></pre></td></tr></table></figure>

<p>有关销毁回调的更多信息，请参看<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/config/Scope.html#registerDestructionCallback" target="_blank" rel="noopener">javadoc</a>或Spring的Scope实现部分。</p>
<p>下面的方法获取相应作用域的区分标识符:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">String <span class="title">getConversationId</span><span class="params">()</span></span></span><br></pre></td></tr></table></figure>

<p>这个标识符在不同的作用域中是不同的。例如对于会话作用域，这个标识符就是会话的标识符。.</p>
<p><a id="beans-factory-scopes-custom-using"></a></p>
<h5 id="使用自定义作用域"><a href="#使用自定义作用域" class="headerlink" title="使用自定义作用域"></a><a href="#beans-factory-scopes-custom-using"></a>使用自定义作用域</h5><p>在实现了自定义<code>作用域</code>后，开发者还需要让Spring容器能够识别发现所创建的新<code>作用域</code>。下面的方法就是在Spring容器中用来注册新<code>Scope</code>的:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">registerScope</span><span class="params">(String scopeName, Scope scope)</span></span>;</span><br></pre></td></tr></table></figure>

<p>这个方法是在<code>ConfigurableBeanFactory</code>的接口中声明的，可以用在多数的<code>ApplicationContext</code>实现，也可以通过 <code>BeanFactory</code>属性来调用。</p>
<p><code>registerScope(..)</code>方法的第一个参数是相关<code>作用域</code>的唯一名称。举例来说，Spring容器中的单例和原型就以它本身来命名。 第二个参数就是开发者希望注册和使用的自定义<code>Scope</code>实现的具有对象 T</p>
<p>假定开发者实现了自定义<code>Scope</code>，然后可以按如下步骤来注册。</p>
<p>下一个示例使用SimpleThreadScope，这个例子在Spring中是有实现的，但没有默认注册。 您自定义的作用域也可以通过如下的方式来注册。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Scope threadScope = <span class="keyword">new</span> SimpleThreadScope();</span><br><span class="line">beanFactory.registerScope(<span class="string">"thread"</span>, threadScope);</span><br></pre></td></tr></table></figure>

<p>然后，您可以创建符合自定义Scope的作用域规则的bean定义，如下所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"..."</span> <span class="attr">class</span>=<span class="string">"..."</span> <span class="attr">scope</span>=<span class="string">"thread"</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在自定义作用域中，开发者也不限于仅仅通过编程的方式来注册作用域，还可以通过配置<code>CustomScopeConfigurer</code> 类来实现。如以下示例所示：:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:aop</span>=<span class="string">"http://www.springframework.org/schema/aop"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/aop</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/aop/spring-aop.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.beans.factory.config.CustomScopeConfigurer"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"scopes"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">map</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"thread"</span>&gt;</span></span><br><span class="line">                    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.context.support.SimpleThreadScope"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;/<span class="name">entry</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">map</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"thing2"</span> <span class="attr">class</span>=<span class="string">"x.y.Thing2"</span> <span class="attr">scope</span>=<span class="string">"thread"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"name"</span> <span class="attr">value</span>=<span class="string">"Rick"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">aop:scoped-proxy</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"thing1"</span> <span class="attr">class</span>=<span class="string">"x.y.Thing1"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"thing2"</span> <span class="attr">ref</span>=<span class="string">"thing2"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在<code>FactoryBean</code>实现中添加了<code>&lt;aop:scoped-proxy/&gt;</code>元素时，它是工厂bean本身的作用域，而不是从<code>getObject()</code>方法返回的对象。</p>
<p><a id="beans-factory-nature"></a></p>
<h3 id="1-6-自定义Bean的特性"><a href="#1-6-自定义Bean的特性" class="headerlink" title="1.6. 自定义Bean的特性"></a><a href="#beans-factory-nature"></a>1.6. 自定义Bean的特性</h3><p>Spring Framework提供了许多可用于自定义bean特性的接口。 本节将它们分组如下：</p>
<ul>
<li><p><a href="#beans-factory-lifecycle">Lifecycle Callbacks(生命周期回调)</a></p>
</li>
<li><p><a href="#beans-factory-aware"><code>ApplicationContextAware</code> and <code>BeanNameAware</code></a></p>
</li>
<li><p><a href="#aware-list">其他 <code>Aware</code> 接口</a></p>
</li>
</ul>
<p><a id="beans-factory-lifecycle"></a></p>
<h4 id="1-6-1-生命周期回调"><a href="#1-6-1-生命周期回调" class="headerlink" title="1.6.1. 生命周期回调"></a><a href="#beans-factory-lifecycle"></a>1.6.1. 生命周期回调</h4><p>你可以实现<code>InitializingBean</code> 和 <code>DisposableBean</code>接口，让容器里管理Bean的生命周期。容器会在调用<code>afterPropertiesSet()</code> 之后和<code>destroy()</code>之前会允许bean在初始化和销毁bean时执行某些操作。</p>
<p>JSR-250 <code>@PostConstruct</code> 和 <code>@PreDestroy</code>注解通常被认为是在现代Spring应用程序中接收生命周期回调的最佳实践。 使用这些注解意味着您的bean不会耦合到特定于Spring的接口。 有关详细信息，请参阅<a href="#beans-postconstruct-and-predestroy-annotations">使用 <code>@PostConstruct</code> 和 <code>@PreDestroy</code></a>.</p>
<p>如果您不想使用JSR-250注解但仍想删除耦合，请考虑使用<code>init-method</code> 和 <code>destroy-method</code>定义对象元数据。</p>
<p>在内部，Spring 框架使用<code>BeanPostProcessor</code> 实现来处理任何回调接口并调用适当的方法。 如果您需要Spring默认提供的自定义功能或其他生命周期行为，您可以自己实现<code>BeanPostProcessor</code>。 有关更多信息，请参阅<a href="#beans-factory-extension">容器扩展点</a>。</p>
<p>除了初始化和销毁方法的回调，Spring管理的对象也实现了Lifecycle接口来让管理的对象在容器的<code>生命周期</code>内启动和关闭。</p>
<p>本节描述了生命周期回调接口。.</p>
<p><a id="beans-factory-lifecycle-initializingbean"></a></p>
<h5 id="初始化方法回调"><a href="#初始化方法回调" class="headerlink" title="初始化方法回调"></a><a href="#beans-factory-lifecycle-initializingbean"></a>初始化方法回调</h5><p><code>org.springframework.beans.factory.InitializingBean</code>接口允许bean在所有的必要的依赖配置完成后执行bean的初始化， <code>InitializingBean</code> 接口中指定使用如下方法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>;</span><br></pre></td></tr></table></figure>

<p>Spring团队是不建议开发者使用<code>InitializingBean</code>接口，因为这样会将代码耦合到Spring的特殊接口上。他们建议使用<a href="#beans-postconstruct-and-predestroy-annotations"><code>@PostConstruct</code></a> 注解或者指定一个POJO的实现方法， 这会比实现接口更好。在基于XML的元数据配置上，开发者可以使用<code>init-method</code> 属性来指定一个没有参数的方法，使用Java配置的开发者可以在<code>@Bean</code>上添加 <code>initMethod</code> 属性。 请参阅 <a href="#beans-java-lifecycle-callbacks">接收生命周期回调</a>接收生命周期回调：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleInitBean"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBean"</span> <span class="attr">init-method</span>=<span class="string">"init"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">public class ExampleBean &#123;</span><br><span class="line"></span><br><span class="line">    public void init() &#123;</span><br><span class="line">        // do some initialization work</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>前面的示例与以下示例（由两个列表组成）具有几乎完全相同的效果：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleInitBean"</span> <span class="attr">class</span>=<span class="string">"examples.AnotherExampleBean"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">public class AnotherExampleBean implements InitializingBean &#123;</span><br><span class="line"></span><br><span class="line">    public void afterPropertiesSet() &#123;</span><br><span class="line">        // do some initialization work</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但是，前面两个示例中的第一个没有将代码耦合到Spring。</p>
<p><a id="beans-factory-lifecycle-disposablebean"></a></p>
<h5 id="销毁方法的回调"><a href="#销毁方法的回调" class="headerlink" title="销毁方法的回调"></a><a href="#beans-factory-lifecycle-disposablebean"></a>销毁方法的回调</h5><p>实现<code>org.springframework.beans.factory.DisposableBean</code> 接口的Bean就能让容器通过回调来销毁bean所引用的资源。 <code>DisposableBean</code> 接口指定一个方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>;</span><br></pre></td></tr></table></figure>

<p>我们建议您不要使用 <code>DisposableBean</code> 回调接口，因为它会不必要地将代码耦合到Spring。或者，我们建议使用<a href="#beans-postconstruct-and-predestroy-annotations"><code>@PreDestroy</code></a>注解 或指定bean定义支持的泛型方法。 在基于XML的元数据配置中，您可以在<code>&lt;bean/&gt;</code>上使用<code>destroy-method</code>属性。 使用Java配置，您可以使用<code>@Bean</code>的 <code>destroyMethod</code> 属性。 请参阅<a href="#beans-java-lifecycle-callbacks">接收生命周期回调</a>。 考虑以下定义：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleInitBean"</span> <span class="attr">class</span>=<span class="string">"examples.ExampleBean"</span> <span class="attr">destroy-method</span>=<span class="string">"cleanup"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">public class ExampleBean &#123;</span><br><span class="line"></span><br><span class="line">    public void cleanup() &#123;</span><br><span class="line">        // do some destruction work (like releasing pooled connections)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>前面的定义与以下定义几乎完全相同：:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"exampleInitBean"</span> <span class="attr">class</span>=<span class="string">"examples.AnotherExampleBean"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">public class AnotherExampleBean implements DisposableBean &#123;</span><br><span class="line"></span><br><span class="line">    public void destroy() &#123;</span><br><span class="line">        // do some destruction work (like releasing pooled connections)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但是，前面两个定义中的第一个没有将代码耦合到Spring。.</p>
<p>您可以为<code>&lt;bean&gt;</code> 元素的<code>destroy-method</code>属性分配一个特殊的（推断的）值，该值指示Spring自动检测特定bean类的<code>close</code>或者<code>shutdown</code>方法。 （因此，任何实现<code>java.lang.AutoCloseable</code>或<code>java.io.Closeable</code>的类都将匹配。） 您还可以在<code>&lt;bean&gt;</code> 元素的<code>default-destroy-method</code>属性上设置此特殊（推断）值，用于让所有的bean都实现这个行为（<a href="#beans-factory-lifecycle-default-init-destroy-methods">参见默认初始化和销毁方法</a>）。 请注意，这是Java配置的默认行为。</p>
<p><a id="beans-factory-lifecycle-default-init-destroy-methods"></a></p>
<h5 id="默认初始化和销毁方法"><a href="#默认初始化和销毁方法" class="headerlink" title="默认初始化和销毁方法"></a><a href="#beans-factory-lifecycle-default-init-destroy-methods"></a>默认初始化和销毁方法</h5><p>当您不使用Spring特有的<code>InitializingBean</code>和 <code>DisposableBean</code>回调接口来实现初始化和销毁方法时，您定义方法的名称最好类似于<code>init()</code>, <code>initialize()</code>, <code>dispose()</code>。 这样可以在项目中标准化类方法，并让所有开发者都使用一样的名字来确保一致性。</p>
<p>您可以配置Spring容器来针对每一个Bean都查找这种名字的初始化和销毁回调方法。也就是说， 任意的开发者都会在应用的类中使用一个叫 <code>init()</code>的初始化回调。而不需要在每个bean中都定义<code>init-method=&quot;init&quot;</code> 这种属性， Spring IoC容器会在bean创建的时候调用那个回调方法（<a href="#beans-factory-lifecycle">如前面描述</a>的标准生命周期一样）。这个特性也将强制开发者为其他的初始化以及销毁回调方法使用同样的名字。</p>
<p>假设您的初始化回调方法名为<code>init()</code>，而您的destroy回调方法名为<code>destroy()</code>。 然后，您的类类似于以下示例中的类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultBlogService</span> <span class="keyword">implements</span> <span class="title">BlogService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> BlogDao blogDao;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBlogDao</span><span class="params">(BlogDao blogDao)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.blogDao = blogDao;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// this is (unsurprisingly) the initialization callback method</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.blogDao == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"The [blogDao] property must be set."</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后，您可以在类似于以下内容的bean中使用该类:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">default-init-method</span>=<span class="string">"init"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"blogService"</span> <span class="attr">class</span>=<span class="string">"com.something.DefaultBlogService"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"blogDao"</span> <span class="attr">ref</span>=<span class="string">"blogDao"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>顶级<code>&lt;beans/&gt;</code>元素属性上存在<code>default-init-method</code>属性会导致Spring IoC容器将bean类上的<code>init</code>方法识别为初始化方法回调。 当bean被创建和组装时，如果bean拥有同名方法的话，则在适当的时候调用它。</p>
<p>您可以使用 <code>&lt;beans/&gt;</code>元素上的<code>default-destroy-method</code>属性，以类似方式（在XML中）配置destroy方法回调。</p>
<p>当某些bean已有的回调方法与配置的默认回调方法不相同时，开发者可以通过特指的方式来覆盖掉默认的回调方法。以XML为例，可以通过使用元素的<code>init-method</code> 和<code>destroy-method</code>属性来覆盖掉<code>&lt;bean/&gt;</code>中的配置。</p>
<p>Spring容器会做出如下保证，bean会在装载了所有的依赖以后，立刻就开始执行初始化回调。这样的话，初始化回调只会在直接的bean引用装载好后调用， 而此时AOP拦截器还没有应用到bean上。首先目标的bean会先完全初始化，然后AOP代理和拦截链才能应用。如果目标bean和代理是分开定义的，那么开发者的代码甚至可以跳过AOP而直接和引用的bean交互。 因此，在初始化方法中应用拦截器会前后矛盾，因为这样做耦合了目标bean的生命周期和代理/拦截器，还会因为与bean产生了直接交互进而引发不可思议的现象。</p>
<p><a id="beans-factory-lifecycle-combined-effects"></a></p>
<h5 id="组合生命周期策略"><a href="#组合生命周期策略" class="headerlink" title="组合生命周期策略"></a><a href="#beans-factory-lifecycle-combined-effects"></a>组合生命周期策略</h5><p>从Spring 2.5开始，您有三种选择用于控制bean生命周期行为:</p>
<ul>
<li><p><a href="#beans-factory-lifecycle-initializingbean"><code>InitializingBean</code></a> 和 <a href="#beans-factory-lifecycle-disposablebean"><code>DisposableBean</code></a> 回调接口</p>
</li>
<li><p>自定义 <code>init()</code> 和 <code>destroy()</code> 方法</p>
</li>
<li><p><a href="#beans-postconstruct-and-predestroy-annotations"><code>@PostConstruct</code> 和 <code>@PreDestroy</code> 注解</a>. 你也可以在bean上同时使用这些机制.</p>
</li>
</ul>
<p>如果bean配置了多个生命周期机制，而且每个机制都配置了不同的方法名字时，每个配置的方法会按照以下描述的顺序来执行。但是，如果配置了相同的名字， 例如初始化回调为<code>init()</code>，在不止一个生命周期机制配置为这个方法的情况下，这个方法只会执行一次。如<a href="#beans-factory-lifecycle-default-init-destroy-methods">上一节中所述</a>。</p>
<p>为同一个bean配置的多个生命周期机制具有不同的初始化方法，如下所示:</p>
<ol>
<li><p>包含<code>@PostConstruct</code>注解的方法</p>
</li>
<li><p>在<code>InitializingBean</code> 接口中的<code>afterPropertiesSet()</code> 方法</p>
</li>
<li><p>自定义的<code>init()</code> 方法</p>
</li>
</ol>
<p>Destroy方法以相同的顺序调用:</p>
<ol>
<li><p>包含<code>@PreDestroy</code>注解的方法</p>
</li>
<li><p>在<code>DisposableBean</code>接口中的<code>destroy()</code> 方法</p>
</li>
<li><p>自定义的<code>destroy()</code> 方法</p>
</li>
</ol>
<p><a id="beans-factory-lifecycle-processor"></a></p>
<h5 id="开始和关闭回调"><a href="#开始和关闭回调" class="headerlink" title="开始和关闭回调"></a><a href="#beans-factory-lifecycle-processor"></a>开始和关闭回调</h5><p><code>Lifecycle</code>接口中为所有具有自定义生命周期需求的对象定义了一些基本方法（例如启动或停止一些后台进程）:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Lifecycle</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">start</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">stop</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isRunning</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>任何Spring管理的对象都可以实现<code>Lifecycle</code> 接口。然后，当<code>ApplicationContext</code>接收到启动和停止信号时（例如，对于运行时的停止/重启场景），ApplicationContext会通知到所有上下文中包含的生命周期对象。 它通过委托 <code>LifecycleProcessor</code>完成此操作，如下面的清单所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">LifecycleProcessor</span> <span class="keyword">extends</span> <span class="title">Lifecycle</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">onRefresh</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">onClose</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>请注意，<code>LifecycleProcessor</code>是 <code>Lifecycle</code>接口的扩展。 它还添加了另外两种方法来响应刷新和关闭的上下文。</p>
<p>注意，常规的<code>org.springframework.context.Lifecycle</code>接口只是为明确的开始/停止通知提供一个约束，而并不表示在上下文刷新就会自动开始。 要对特定bean的自动启动（包括启动阶段）进行细粒度控制，请考虑实现<code>org.springframework.context.SmartLifecycle</code>接口。</p>
<p>同时，停止通知并不能保证在销毁之前出现。在正常的关闭情况下，所有的<code>Lifecycle</code>都会在销毁回调准备好之前收到停止通知，然而， 在上下文生命周期中的热刷新或者停止尝试刷新时，则只会调用销毁方法。</p>
<p>启动和关闭调用的顺序非常重要。如果任何两个对象之间存在“依赖”关系，则依赖方在其依赖之后开始，并且在其依赖之前停止。但是，有时，直接依赖性是未知的。 您可能只知道某种类型的对象应该在另一种类型的对象之前开始。 在这些情况下， <code>SmartLifecycle</code>接口定义了另一个选项，即在其超级接口<code>Phased</code> 上定义的 <code>getPhase()</code> 方法。 以下清单显示了<code>Phased</code>接口的定义</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Phased</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">getPhase</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以下清单显示了<code>SmartLifecycle</code>接口的定义:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">SmartLifecycle</span> <span class="keyword">extends</span> <span class="title">Lifecycle</span>, <span class="title">Phased</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isAutoStartup</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">stop</span><span class="params">(Runnable callback)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当启动时，拥有最低phased的对象会优先启动，而当关闭时，会相反的顺序执行。因此，如果一个对象实现了<code>SmartLifecycle</code>，然后令其<code>getPhase()</code>方法返回<code>Integer.MIN_VALUE</code>值的话， 就会让该对象最早启动，而最晚销毁。显然，如果<code>getPhase()</code>方法返回了<code>Integer.MAX_VALUE</code>值则表明该对象会最晚启动，而最早销毁。 当考虑到使用phased值时，也同时需要了解正常没有实现<code>SmartLifecycle</code>的<code>Lifecycle</code>对象的默认值，这个值是0。因此，配置任意的负值都将表明将对象会在标准组件启动之前启动 ，而在标准组件销毁以后再进行销毁。</p>
<p><code>SmartLifecycle</code>接口也定义了一个名为stop的回调方法，任何实现了<code>SmartLifecycle</code>接口的方法都必须在关闭流程完成之后调用回调中的<code>run()</code>方法。 这样做可以进行异步关闭，而<code>lifecycleProcessor</code>的默认实现<code>DefaultLifecycleProcessor</code>会等到配置的超时时间之后再调用回调。默认的每一阶段的超时时间为30秒。 您可以通过在上下文中定义名为 <code>lifecycleProcessor</code> 的bean来覆盖默认生命周期处理器实例。 如果您只想修改超时，则定义以下内容就足够了：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"lifecycleProcessor"</span> <span class="attr">class</span>=<span class="string">"org.springframework.context.support.DefaultLifecycleProcessor"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- timeout value in milliseconds --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"timeoutPerShutdownPhase"</span> <span class="attr">value</span>=<span class="string">"10000"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>如前所述，<code>LifecycleProcessor</code> 接口还定义了用于刷新和关闭上下文的回调方法。在关闭过程中，如果<code>stop()</code>方法已经被调用，则就会执行关闭流程。 但是如果上下文正在关闭中则不会在进行此流程，而刷新的回调会使用到<code>SmartLifecycle</code>的另一个特性。当上下文刷新完毕（所有的对象已经实例化并初始化）后， 就会调用刷新回调，默认的生命周期处理器会检查每一个<code>SmartLifecycle</code> 对象的<code>isAutoStartup()</code>方法返回的Boolean值.如果为真，对象将会自动启动而不是等待明确的上下文调用， 或者调用自己的<code>start()</code>方法(不同于上下文刷新，标准的上下文实现是不会自动启动的）。<code>phase</code>的值以及“depends-on”关系会决定对象启动和销毁的顺序。</p>
<p><a id="beans-factory-shutdown"></a></p>
<h5 id="在非Web应用中优雅地关闭Spring-IoC容器"><a href="#在非Web应用中优雅地关闭Spring-IoC容器" class="headerlink" title="在非Web应用中优雅地关闭Spring IoC容器"></a><a href="#beans-factory-shutdown"></a>在非Web应用中优雅地关闭Spring IoC容器</h5><p>本节仅适用于非Web应用程序。 Spring的基于Web的<code>ApplicationContext</code> 实现已经具有代码，可以在关闭相关Web应用程序时正常关闭Spring IoC容器。</p>
<p>如果开发者在非Web应用环境使用Spring IoC容器的话（例如，在桌面客户端的环境下）开发者需要在JVM上注册一个关闭的钩子，来确保在关闭Spring IoC容器的时候能够调用相关的销毁方法来释放掉引用的资源。 当然，开发者也必须正确配置和实现那些销毁回调。</p>
<p>要注册关闭钩子，请调用<code>ConfigurableApplicationContext</code>接口上声明的<code>registerShutdownHook()</code> 方法，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.ConfigurableApplicationContext;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Boot</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(<span class="keyword">final</span> String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ConfigurableApplicationContext ctx = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"beans.xml"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// add a shutdown hook for the above context...</span></span><br><span class="line">        ctx.registerShutdownHook();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// app runs here...</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// main method exits, hook is called prior to the app shutting down...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-factory-aware"></a></p>
<h4 id="1-6-2-ApplicationContextAware-和-BeanNameAware"><a href="#1-6-2-ApplicationContextAware-和-BeanNameAware" class="headerlink" title="1.6.2. ApplicationContextAware 和 BeanNameAware"></a><a href="#beans-factory-aware"></a>1.6.2. <code>ApplicationContextAware</code> 和 <code>BeanNameAware</code></h4><p>当<code>ApplicationContext</code> 创建实现<code>org.springframework.context.ApplicationContextAware</code>接口的对象实例时，将为该实例提供对该 <code>ApplicationContext</code>.的引用。 以下清单显示了<code>ApplicationContextAware</code>接口的定义：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ApplicationContextAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(ApplicationContext applicationContext)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样bean就能够通过编程的方式创建和操作<code>ApplicationContext</code> 了。通过<code>ApplicationContext</code> 接口，或者通过将引用转换成已知的接口的子类， 例如<code>ConfigurableApplicationContext</code>就能够提供一些额外的功能。其中的一个用法就是可以通过编程的方式来获取其他的bean。 有时候这个能力非常有用。当然，Spring团队并不推荐这样做，因为这样会使代码与Spring框架耦合，同时也没有遵循IoC的风格。 <code>ApplicationContext</code> 中其它的方法可以提供一些诸如资源的访问、发布应用事件或者添加<code>MessageSource</code>之类的功能。<a href="#context-introduction"><code>ApplicationContext</code>的附加功能</a>中描述了这些附加功能。</p>
<p>从Spring 2.5开始， 自动装配是另一种获取<code>ApplicationContext</code>引用的替代方法。传统的的<code>构造函数</code> 和 <code>byType</code>的装载方式自动装配模式（如<a href="#beans-factory-autowire">自动装配</a>中所述） 可以通过构造函数或setter方法的方式注入，开发者也可以通过注解注入的方式。为了更为方便，包括可以注入的字段和多个参数方法，请使用新的基于注解的自动装配功能。 这样，<code>ApplicationContext</code>将自动装配字段、构造函数参数或方法参数，如果相关的字段，构造函数或方法带有 <code>@Autowired</code>注解，则该参数需要<code>ApplicationContext</code>类型。 有关更多信息，请参阅<a href="#beans-autowired-annotation">使用 <code>@Autowired</code></a>@Autowired。</p>
<p>当<code>ApplicationContext</code>创建实现了<code>org.springframework.beans.factory.BeanNameAware</code>接口的类，那么这个类就可以针对其名字进行配置。以下清单显示了BeanNameAware接口的定义：:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BeanNameAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">setBeanName</span><span class="params">(String name)</span> <span class="keyword">throws</span> BeansException</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个回调的调用在属性配置完成之后，但是在初始化回调之前。例如<code>InitializingBean</code>, <code>afterPropertiesSet</code>方法以及自定义的初始化方法等。</p>
<p><a id="aware-list"></a></p>
<h4 id="1-6-3-其他的-Aware接口"><a href="#1-6-3-其他的-Aware接口" class="headerlink" title="1.6.3. 其他的 Aware接口"></a><a href="#aware-list"></a>1.6.3. 其他的 <code>Aware</code>接口</h4><p>除了 <code>ApplicationContextAware</code>和<code>BeanNameAware</code>（前面已讨论过）之外，Spring还提供了一系列<code>Aware</code>接口，让bean告诉容器，它们需要一些具体的基础配置信息。。 一些重要的<code>Aware</code>接口参看下表：</p>
<p>Table 4. Aware 接口</p>
<table>
<thead>
<tr>
<th>名称</th>
<th>注入的依赖</th>
<th>所对应的章节</th>
</tr>
</thead>
<tbody><tr>
<td><code>ApplicationContextAware</code></td>
<td>声明 <code>ApplicationContext</code></td>
<td><a href="#beans-factory-aware"><code>ApplicationContextAware</code> 和 <code>BeanNameAware</code></a></td>
</tr>
<tr>
<td><code>ApplicationEventPublisherAware</code></td>
<td><code>ApplicationContext</code>的事件发布者</td>
<td><a href="#context-introduction"><code>ApplicationContext</code>的其他功能</a></td>
</tr>
<tr>
<td><code>BeanClassLoaderAware</code></td>
<td>用于加载bean类的类加载器</td>
<td><a href="#beans-factory-class">实例化Bean</a></td>
</tr>
<tr>
<td><code>BeanFactoryAware</code></td>
<td>声明 <code>BeanFactory</code>.</td>
<td><a href="#beans-factory-aware"><code>ApplicationContextAware</code> 和 <code>BeanNameAware</code></a></td>
</tr>
<tr>
<td><code>BeanNameAware</code></td>
<td>声明bean的名称.</td>
<td><a href="#beans-factory-aware"><code>ApplicationContextAware</code> 和 <code>BeanNameAware</code></a></td>
</tr>
<tr>
<td><code>BootstrapContextAware</code></td>
<td>容器运行的资源适配器<code>BootstrapContext</code>。通常仅在JCA感知的 <code>ApplicationContext</code> 实例中可用</td>
<td><a href="https://github.com/DocsHome/spring-docs/blob/master/pages/integration/integration.md#cci" target="_blank" rel="noopener">JCA CCI</a></td>
</tr>
<tr>
<td><code>LoadTimeWeaverAware</code></td>
<td>定义的weaver用于在加载时处理类定义.</td>
<td><a href="#aop-aj-ltw">在Spring框架中使用AspectJ进行加载时织入</a></td>
</tr>
<tr>
<td><code>MessageSourceAware</code></td>
<td>用于解析消息的已配置策略（支持参数化和国际化）</td>
<td><a href="#context-introduction"><code>ApplicationContext</code>的其他作用</a></td>
</tr>
<tr>
<td><code>NotificationPublisherAware</code></td>
<td>Spring JMX通知发布者</td>
<td><a href="https://github.com/DocsHome/spring-docs/blob/master/pages/integration/integration.md#jmx-notifications" target="_blank" rel="noopener">通知</a></td>
</tr>
<tr>
<td><code>ResourceLoaderAware</code></td>
<td>配置的资源加载器</td>
<td><a href="#resources">资源</a></td>
</tr>
<tr>
<td><code>ServletConfigAware</code></td>
<td>当前<code>ServletConfig</code>容器运行。仅在Web下的Spring <code>ApplicationContext</code>中有效</td>
<td><a href="https://github.com/DocsHome/spring-docs/blob/master/pages/web/web.md#mvc" target="_blank" rel="noopener">Spring MVC</a></td>
</tr>
<tr>
<td><code>ServletContextAware</code></td>
<td>容器运行的当前ServletContext。仅在Web下的Spring <code>ApplicationContext</code>中有效。</td>
<td><a href="https://github.com/DocsHome/spring-docs/blob/master/pages/web/web.md#mvc" target="_blank" rel="noopener">Spring MVC</a></td>
</tr>
</tbody></table>
<p>请再次注意，使用这些接口会将您的代码绑定到Spring API，而不会遵循IoC原则。 因此，我们建议将它们用于需要以编程方式访问容器的基础架构bean。</p>
<p><a id="beans-child-bean-definitions"></a></p>
<h3 id="1-7-bean定义的继承"><a href="#1-7-bean定义的继承" class="headerlink" title="1.7. bean定义的继承"></a><a href="#beans-child-bean-definitions"></a>1.7. bean定义的继承</h3><p>bean定义可以包含许多配置信息，包括构造函数参数，属性值和特定于容器的信息，例如初始化方法，静态工厂方法名称等。 子bean定义从父定义继承配置数据。 子定义可以覆盖某些值或根据需要添加其他值。 使用父子bean定义可以节省很多配置输入。 实际上，这是一种模板形式。</p>
<p>如果开发者编程式地使用<code>ApplicationContext</code>接口，子bean定义可以通过<code>ChildBeanDefinition</code>类来表示。很多开发者不会使用这个级别的方法， 而是会在类似于<code>ClassPathXmlApplicationContext</code>中声明式地配置bean定义。当你使用基于XML的配置时，你可以在子bean中使用parent属性，该属性的值用来识别父bean。 以下示例显示了如何执行此操作：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"inheritedTestBean"</span> <span class="attr">abstract</span>=<span class="string">"true"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">"org.springframework.beans.TestBean"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"name"</span> <span class="attr">value</span>=<span class="string">"parent"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"age"</span> <span class="attr">value</span>=<span class="string">"1"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"inheritsWithDifferentClass"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">"org.springframework.beans.DerivedTestBean"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">parent</span>=<span class="string">"inheritedTestBean"</span> <span class="attr">init-method</span>=<span class="string">"initialize"</span>&gt;</span>  (1)</span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"name"</span> <span class="attr">value</span>=<span class="string">"override"</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- the age property value of 1 will be inherited from parent --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>1</strong>。请注意<code>parent</code>属性。</p>
<p>子bean如果没有指定class，它将使用父bean定义的class。但也可以进行重写。在后一种情况中，子bean必须与父bean兼容，也就是说，它必须接受父bean的属性值。</p>
<p>子bean定义从父类继承作用域、构造器参数、属性值和可重写的方法，除此之外，还可以增加新值。开发者指定任何作用域、初始化方法、销毁方法和/或者静态工厂方法设置都会覆盖相应的父bean设置。</p>
<p>剩下的设置会取子bean定义：依赖、自动注入模式、依赖检查、单例、延迟加载。</p>
<p>前面的示例通过使用<code>abstract</code>属性将父bean定义显式标记为<code>abstract</code>。 如果父定义未指定类，则需要将父bean定义显式标记为<code>abstract</code>，如以下示例所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"inheritedTestBeanWithoutClass"</span> <span class="attr">abstract</span>=<span class="string">"true"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"name"</span> <span class="attr">value</span>=<span class="string">"parent"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"age"</span> <span class="attr">value</span>=<span class="string">"1"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"inheritsWithClass"</span> <span class="attr">class</span>=<span class="string">"org.springframework.beans.DerivedTestBean"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">parent</span>=<span class="string">"inheritedTestBeanWithoutClass"</span> <span class="attr">init-method</span>=<span class="string">"initialize"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"name"</span> <span class="attr">value</span>=<span class="string">"override"</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- age will inherit the value of 1 from the parent bean definition--&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>父bean不能单独实例化，因为它不完整，并且也明确标记为<code>abstract</code>。当定义是<code>abstract</code>的时，它只能用作纯模板bean定义，用作子定义的父定义。如果试图单独地使用声明了<code>abstract</code>的父bean， 通过引用它作为另一个bean的ref属性，或者使用父bean id进行显式的<code>getBean()</code>调用，都将返回一个错误。同样，容器内部的 <code>preInstantiateSingletons()</code>方法也会忽略定义为<code>abstract</code>的bean。</p>
<p><code>ApplicationContext</code> 默认会预先实例化所有的单例bean。因此，如果开发者打算把(父）bean定义仅仅作为模板来使用，同时为它指定了class属性， 那么必须确保设置_abstract_的属性值为true。否则，应用程序上下文会(尝试）预实例化这个<code>abstract</code> bean。</p>
<p><a id="beans-factory-extension"></a></p>
<h3 id="1-8-容器的扩展点"><a href="#1-8-容器的扩展点" class="headerlink" title="1.8. 容器的扩展点"></a><a href="#beans-factory-extension"></a>1.8. 容器的扩展点</h3><p>通常，应用程序开发者无需继承<code>ApplicationContext</code>的实现类。相反，Spring IoC容器可以通过插入特殊的集成接口实现进行扩展。接下来的几节将介绍这些集成接口。</p>
<p><a id="beans-factory-extension-bpp"></a></p>
<h4 id="1-8-1-使用BeanPostProcessor自定义Bean"><a href="#1-8-1-使用BeanPostProcessor自定义Bean" class="headerlink" title="1.8.1. 使用BeanPostProcessor自定义Bean"></a><a href="#beans-factory-extension-bpp"></a>1.8.1. 使用<code>BeanPostProcessor</code>自定义Bean</h4><p><code>BeanPostProcessor</code>接口定义了可以实现的回调方法，以提供您自己的（或覆盖容器的默认）实例化逻辑，依赖关系解析逻辑等。 如果要在Spring容器完成实例化，配置和初始化bean之后实现某些自定义逻辑，则可以插入一个或多个<code>BeanPostProcessor</code>实现。</p>
<p>您可以配置多个<code>BeanPostProcessor</code> 实例，并且可以通过设置<code>order</code>属性来控制这些 <code>BeanPostProcessor</code> 实例的执行顺序。 仅当<code>BeanPostProcessor</code>实现 <code>Ordered</code>接口时，才能设置此属性。如果编写自己的<code>BeanPostProcessor</code>，则应考虑实现Ordered接口。 有关更多详细信息， 请参阅<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/config/BeanPostProcessor.html" target="_blank" rel="noopener"><code>BeanPostProcessor</code></a> 和 <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/core/Ordered.html" target="_blank" rel="noopener"><code>Ordered</code></a>的javadoc。 另请参阅有关<a href="#beans-factory-programmatically-registering-beanpostprocessors"><code>BeanPostProcessor</code> 实例</a>的编程注册的说明。</p>
<p><code>BeanPostProcessor</code>实例在bean（或对象）实例上运行。 也就是说，Spring IoC容器实例化一个bean实例，然后才能用<code>BeanPostProcessor</code> 对这个实例进行处理。</p>
<p><code>BeanPostProcessor</code>会在整个容器内起作用，所有它仅仅与正在使用的容器相关。如果在一个容器中定义了<code>BeanPostProcessor</code>，那么它只会处理那个容器中的bean。 换句话说，在一个容器中定义的bean不会被另一个容器定义的<code>BeanPostProcessor</code>处理，即使这两个容器都是同一层次结构的一部分。</p>
<p>要更改实际的bean定义（即定义bean的蓝图），您需要使用<code>BeanFactoryPostProcessor</code>，使用BeanFactoryPostProcessor自定义配置元数据。 <a href="#beans-factory-extension-factory-postprocessors">使用 <code>BeanFactoryPostProcessor</code>自定义配置元数据</a>.</p>
<p><code>org.springframework.beans.factory.config.BeanPostProcessor</code>接口由两个回调方法组成，当一个类被注册为容器的后置处理器时，对于容器创建的每个bean实例， 后置处理器都会在容器初始化方法（如<code>InitializingBean.afterPropertiesSet()</code>之前和容器声明的<code>init</code>方法）以及任何bean初始化回调之后被调用。后置处理器可以对bean实例执行任何操作， 包括完全忽略回调。bean后置处理器，通常会检查回调接口或者使用代理包装bean。一些Spring AOP基础架构类为了提供包装好的代理逻辑，会被实现为bean后置处理器。</p>
<p><code>ApplicationContext</code>会自动地检测所有定义在配置元文件中，并实现了<code>BeanPostProcessor</code> 接口的bean。<code>ApplicationContext</code>会注册这些beans为后置处理器， 使他们可以在bean创建完成之后被调用。bean后置处理器可以像其他bean一样部署到容器中。</p>
<p>当在配置类上使用 <code>@Bean</code> 工厂方法声明<code>BeanPostProcessor</code>时，工厂方法返回的类型应该是实现类自身。，或至少也是<code>org.springframework.beans.factory.config.BeanPostProcessor</code>接口， 要清楚地表明这个bean的后置处理器的本质特点。否则，在它完全创建之前，<code>ApplicationContext</code>将不能通过类型自动探测它。由于<code>BeanPostProcessor</code>在早期就需要被实例化， 以适应上下文中其他bean的实例化，因此这个早期的类型检查是至关重要的。</p>
<p>以编程方式注册<code>BeanPostProcessor</code>实例，虽然<code>BeanPostProcessor</code>注册的推荐方法是通过<code>ApplicationContext</code>自动检测（如前所述），但您可以以编程的方式使用<code>ConfigurableBeanFactory</code>的<code>addBeanPostProcessor</code>方法进行注册。 这对于在注册之前需要对条件逻辑进行评估，或者是在继承层次的上下文之间复制bean的后置处理器中是有很有用的。 但请注意，以编程方式添加的<code>BeanPostProcessor</code>实例不遵循<code>Ordered</code>接口。这里，注册顺序决定了执行的顺序。 另请注意，以编程方式注册的<code>BeanPostProcessor</code>实例始终在通过自动检测注册的实例之前处理，而不管任何显式排序。</p>
<p><code>BeanPostProcessor</code> 实例 and AOP 自动代理</p>
<p>实现<code>BeanPostProcessor</code> 接口的类是特殊的，容器会对它们进行不同的处理。所有<code>BeanPostProcessor</code> 和他们直接引用的beans都会在容器启动的时候被实例化， 并作为<code>ApplicationContext</code>特殊启动阶段的一部分。接着，所有的<code>BeanPostProcessor</code> 都会以一个有序的方式进行注册，并应用于容器中的所有bean。 因为AOP自动代理本身被实现为<code>BeanPostProcessor</code>，这个<code>BeanPostProcessor</code>和它直接应用的beans都不适合进行自动代理，因此也就无法在它们中织入切面。</p>
<p>对于所有这样的bean，您应该看到一条信息性日志消息: <code>Bean someBean is not eligible for getting processed by all BeanPostProcessor interfaces (for example: not eligible for auto-proxying)</code>.</p>
<p>如果你使用自动装配或 <code>@Resource</code>（可能会回退到自动装配）将Bean连接到<code>BeanPostProcessor</code>中，Spring可能会在搜索类型匹配的依赖关系候选时访问到意外类型的bean； 因此，对它们不适合进行自动代理，或者对其他类型的bean进行后置处理。例如，如果有一个使用 <code>@Resource</code> 注解的依赖项，其中字段或setter名称不直接对应于bean的声明名称而且没有使用name属性， 则Spring会访问其他bean以按类型匹配它们。</p>
<p>以下示例显示如何在<code>ApplicationContext</code>中编写，注册和使用<code>BeanPostProcessor</code>实例。</p>
<p><a id="beans-factory-extension-bpp-examples-hw"></a></p>
<h5 id="示例-Hello-World-BeanPostProcessor-style"><a href="#示例-Hello-World-BeanPostProcessor-style" class="headerlink" title="示例: Hello World, BeanPostProcessor-style"></a><a href="#beans-factory-extension-bpp-examples-hw"></a>示例: Hello World, <code>BeanPostProcessor</code>-style</h5><p>第一个例子说明了基本用法。 该示例显示了一个自定义<code>BeanPostProcessor</code>实现，该实现在容器创建时调用每个bean的 <code>toString()</code> 方法，并将生成的字符串输出到系统控制台。</p>
<p>以下清单显示了自定义<code>BeanPostProcessor</code> 实现类定义:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> scripting;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.config.BeanPostProcessor;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InstantiationTracingBeanPostProcessor</span> <span class="keyword">implements</span> <span class="title">BeanPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// simply return the instantiated bean as-is</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> bean; <span class="comment">// we could potentially return any object reference here...</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Bean '"</span> + beanName + <span class="string">"' created : "</span> + bean.toString());</span><br><span class="line">        <span class="keyword">return</span> bean;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以下beans元素使用<code>InstantiationTracingBeanPostProcessor</code>:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:lang</span>=<span class="string">"http://www.springframework.org/schema/lang"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/lang</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/lang/spring-lang.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">lang:groovy</span> <span class="attr">id</span>=<span class="string">"messenger"</span></span></span><br><span class="line"><span class="tag">            <span class="attr">script-source</span>=<span class="string">"classpath:org/springframework/scripting/groovy/Messenger.groovy"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">lang:property</span> <span class="attr">name</span>=<span class="string">"message"</span> <span class="attr">value</span>=<span class="string">"Fiona Apple Is Just So Dreamy."</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">lang:groovy</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">    when the above bean (messenger) is instantiated, this custom</span></span><br><span class="line"><span class="comment">    BeanPostProcessor implementation will output the fact to the system console</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"scripting.InstantiationTracingBeanPostProcessor"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>注意<code>InstantiationTracingBeanPostProcessor</code>是如何定义的，它甚至没有名字，因为它是一个bean，所以它可以像任何其他bean一样进行依赖注入 （前面的配置还定义了一个由Groovy脚本支持的bean。在<a href="https://github.com/DocsHome/spring-docs/blob/master/pages/languages/languages.md#dynamic-language" target="_blank" rel="noopener">动态语言支持</a>一章中详细介绍了Spring动态语言支持）。</p>
<p>下面简单的Java应用执行了前面代码和配置:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.ApplicationContext;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;</span><br><span class="line"><span class="keyword">import</span> org.springframework.scripting.Messenger;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Boot</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(<span class="keyword">final</span> String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        ApplicationContext ctx = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"scripting/beans.xml"</span>);</span><br><span class="line">        Messenger messenger = (Messenger) ctx.getBean(<span class="string">"messenger"</span>);</span><br><span class="line">        System.out.println(messenger);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述应用程序的输出类似于以下内容:</p>
<p>Bean ‘messenger’ created :  org.springframework.scripting.groovy.GroovyMessenger@272961<br>org.springframework.scripting.groovy.GroovyMessenger@272961</p>
<p><a id="beans-factory-extension-bpp-examples-rabpp"></a></p>
<h5 id="示例-The-RequiredAnnotationBeanPostProcessor"><a href="#示例-The-RequiredAnnotationBeanPostProcessor" class="headerlink" title="示例: The RequiredAnnotationBeanPostProcessor"></a><a href="#beans-factory-extension-bpp-examples-rabpp"></a>示例: The <code>RequiredAnnotationBeanPostProcessor</code></h5><p>自定义<code>BeanPostProcessor</code>实现与回调接口或注解配合使用，是一种常见的扩展Spring IoC容器手段，一个例子就是<code>RequiredAnnotationBeanPostProcessor</code>，这是<code>BeanPostProcessor</code>实现。 它确保用（任意）注解标记的bean上的JavaBean属性实际上（配置为）依赖注入值。</p>
<p><a id="beans-factory-extension-factory-postprocessors"></a></p>
<h4 id="1-8-2-使用BeanFactoryPostProcessor自定义元数据配置"><a href="#1-8-2-使用BeanFactoryPostProcessor自定义元数据配置" class="headerlink" title="1.8.2. 使用BeanFactoryPostProcessor自定义元数据配置"></a><a href="#beans-factory-extension-factory-postprocessors"></a>1.8.2. 使用<code>BeanFactoryPostProcessor</code>自定义元数据配置</h4><p>下一个我们要关注的扩展点是<code>org.springframework.beans.factory.config.BeanFactoryPostProcessor</code>。这个接口的语义与<code>BeanPostProcessor</code>类似， 但有一处不同，<code>BeanFactoryPostProcessor</code>操作bean的元数据配置。也就是说，也就是说，Spring IoC容器允许<code>BeanFactoryPostProcessor</code>读取配置元数据， 并可能在容器实例化除<code>BeanFactoryPostProcessor</code>实例之外的任何bean之前更改它。</p>
<p>您可以配置多个<code>BeanFactoryPostProcessor</code>实例，并且可以通过设置<code>order</code>属性来控制这些<code>BeanFactoryPostProcessor</code>实例的运行顺序（<code>BeanFactoryPostProcessor</code>必须实现了<code>Ordered</code>接口才能设置这个属性）。 如果编写自己的BeanFactoryPostProcessor，则应考虑实现Ordered接口。 有关更多详细信息， 请参阅<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/config/BeanFactoryPostProcessor.html" target="_blank" rel="noopener"><code>BeanFactoryPostProcessor</code></a> 和 <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/core/Ordered.html" target="_blank" rel="noopener"><code>Ordered</code></a> 接口的javadoc.</p>
<p>如果想修改实际的bean实例（也就是说，从元数据配置中创建的对象）那么需要使用<code>BeanPostProcessor</code>（前面在使用<a href="#beans-factory-extension-bpp"><code>BeanPostProcessor</code>自定义Bean</a>中进行了描述）来替代。 在<code>BeanFactoryPostProcessor</code>（例如使用<code>BeanFactory.getBean()</code>）中使用这些bean的实例虽然在技术上是可行的，但这么来做会将bean过早实例化， 这违反了标准的容器生命周期。同时也会引发一些副作用，例如绕过bean的后置处理。</p>
<p><code>BeanFactoryPostProcessor</code>会在整个容器内起作用，所有它仅仅与正在使用的容器相关。如果在一个容器中定义了<code>BeanFactoryPostProcessor</code>， 那么它只会处理那个容器中的bean。 换句话说，在一个容器中定义的bean不会被另一个容器定义的<code>BeanFactoryPostProcessor</code>处理，即使这两个容器都是同一层次结构的一部分。</p>
<p>bean工厂后置处理器在<code>ApplicationContext</code>中声明时自动执行，这样就可以对定义在容器中的元数据配置进行修改。 Spring包含许多预定义的bean工厂后处理器， 例如<code>PropertyOverrideConfigurer</code> 和<code>PropertyPlaceholderConfigurer</code>。 您还可以使用自定义<code>BeanFactoryPostProcessor</code>。 例如，注册自定义属性编辑器。 .</p>
<p><code>ApplicationContext</code> 自动检测部署到其中的任何实现<code>BeanFactoryPostProcessor</code>接口的bean。 它在适当的时候使用这些bean作为bean工厂后置处理器。 你可以部署这些后置处理器为你想用的任意其它bean。</p>
<p>注意，和<code>BeanPostProcessor</code>一样，通常不应该配置<code>BeanFactoryPostProcessor</code>来进行延迟初始化。如果没有其它bean引用<code>Bean(Factory)PostProcessor</code>， 那么后置处理器就不会被初始化。因此，标记它为延迟初始化就会被忽略，，即便你在<code>&lt;beans /&gt;</code>元素声明中设置<code>default-lazy-init</code>=true属性，<code>Bean(Factory)PostProcessor</code>也会提前初始化bean。</p>
<p><a id="beans-factory-placeholderconfigurer"></a></p>
<h5 id="示例-类名替换PropertyPlaceholderConfigurer"><a href="#示例-类名替换PropertyPlaceholderConfigurer" class="headerlink" title="示例: 类名替换PropertyPlaceholderConfigurer"></a><a href="#beans-factory-placeholderconfigurer"></a>示例: 类名替换<code>PropertyPlaceholderConfigurer</code></h5><p>您可以使用<code>PropertyPlaceholderConfigurer</code>通过使用标准Java <code>Properties</code>格式从单独文件中的bean定义外部化属性值。 这样做可以使部署应用程序的人能够定制特定于环境的属性，如数据库URL和密码，而无需修改容器的主XML定义文件或文件的复杂性或风险。</p>
<p>考虑以下这个基于XML的元数据配置代码片段，这里的DataSource使用了占位符来定义:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"locations"</span> <span class="attr">value</span>=<span class="string">"classpath:com/something/jdbc.properties"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"dataSource"</span> <span class="attr">destroy-method</span>=<span class="string">"close"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">"org.apache.commons.dbcp.BasicDataSource"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driverClassName"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.driverClassName&#125;"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"url"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.url&#125;"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.username&#125;"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.password&#125;"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>该示例显示了从外部属性文件配置的属性。在运行时，<code>PropertyPlaceholderConfigurer</code>应用于替换DataSource的某些属性的元数据。 要替换的值被指定为$ {property-name}形式的占位符，它遵循Ant和log4j以及JSP EL样式。</p>
<p>而真正的值是来自于标准的Java <code>Properties</code>格式的文件:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">jdbc.driverClassName&#x3D;org.hsqldb.jdbcDriver</span><br><span class="line">jdbc.url&#x3D;jdbc:hsqldb:hsql:&#x2F;&#x2F;production:9002</span><br><span class="line">jdbc.username&#x3D;sa</span><br><span class="line">jdbc.password&#x3D;root</span><br></pre></td></tr></table></figure>

<p>在上面的例子中，<code>${jdbc.username}</code> 字符串在运行时将替换为值’sa’，并且同样适用于与属性文件中的键匹配的其他占位符值。 <code>PropertyPlaceholderConfigurer</code>检查bean定义的大多数属性和属性中的占位符。 此外，您可以自定义占位符前缀和后缀。</p>
<p>使用Spring 2.5中引入的<code>context</code> 命名空间，您可以使用专用配置元素配置属性占位符。 您可以在<code>location</code>属性中以逗号分隔列表的形式提供一个或多个位置，如以下示例所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">context:property-placeholder</span> <span class="attr">location</span>=<span class="string">"classpath:com/something/jdbc.properties"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>PropertyPlaceholderConfigurer</code>不仅在您指定的属性文件中查找属性。 默认情况下，如果它在指定的属性文件中找不到属性，它还会检查Java <code>System</code>属性。 开发者可以通过设置<code>systemPropertiesMode</code>属性，使用下面三个整数的某一个来自定义这种行为：</p>
<ul>
<li><p><code>never</code> (0): 从不检查系统属性。</p>
</li>
<li><p><code>fallback</code> (1): 如果没有在指定的属性文件中解析到属性，那么就检查系统属性（默认）。</p>
</li>
<li><p><code>override</code> (2): 在检查指定的属性文件之前，首先去检查系统属性，允许系统属性覆盖其它任意的属性资源。</p>
</li>
</ul>
<p>有关更多信息，请参见<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html" target="_blank" rel="noopener"><code>PropertyPlaceholderConfigurer</code></a> javadoc</p>
<p>你可以使用<code>PropertyPlaceholderConfigurer</code>来替换类名，当开发者在运行时需要选择某个特定的实现类时，这是很有用的。例如</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"locations"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">value</span>&gt;</span>classpath:com/something/strategy.properties<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"properties"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">value</span>&gt;</span>custom.strategy.class=com.something.DefaultStrategy<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"serviceStrategy"</span> <span class="attr">class</span>=<span class="string">"$&#123;custom.strategy.class&#125;"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>如果在运行时无法将类解析为有效类，则在即将创建bean时，bean的解析将失败，这是 <code>ApplicationContext</code>在对非延迟初始化bean的<code>preInstantiateSingletons()</code>阶段发生的事。</p>
<p><a id="beans-factory-overrideconfigurer"></a></p>
<h5 id="示例-PropertyOverrideConfigurer"><a href="#示例-PropertyOverrideConfigurer" class="headerlink" title="示例: PropertyOverrideConfigurer"></a><a href="#beans-factory-overrideconfigurer"></a>示例: <code>PropertyOverrideConfigurer</code></h5><p><code>PropertyOverrideConfigurer</code>, 另外一种bean工厂后置处理器，类似于<code>PropertyPlaceholderConfigurer</code>，但与后者不同的是：对于所有的bean属性，原始定义可以有默认值或也可能没有值。 如果一个<code>Properties</code>覆盖文件没有配置特定的bean属性，则就会使用默认的上下文定义</p>
<p>注意，bean定义是不知道是否被覆盖的，所以从XML定义文件中不能马上看到那个配置正在被使用。在拥有多个<code>PropertyOverrideConfigurer</code> 实例的情况下，为相同bean的属性定义不同的值时，基于覆盖机制只会有最后一个生效。</p>
<p>属性文件配置行采用以下格式:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">beanName.property&#x3D;value</span><br></pre></td></tr></table></figure>

<p>例如:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">dataSource.driverClassName&#x3D;com.mysql.jdbc.Driver</span><br><span class="line">dataSource.url&#x3D;jdbc:mysql:mydb</span><br></pre></td></tr></table></figure>

<p>这个示例文件可以和容器定义一起使用，该容器定义包含一个名为<code>dataSource</code>的bean，该bean具有 <code>driver</code>和<code>url</code>属性</p>
<p>复合属性名称也是被支持的，只要被重写的最后一个属性以外的路径中每个组件都已经是非空时（假设由构造方法初始化）。 在下面的示例中，<code>tom</code> bean的<code>fred</code>属性的 <code>bob</code>属性的<code>sammy</code>属性设置值为<code>123</code>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tom.fred.bob.sammy&#x3D;123</span><br></pre></td></tr></table></figure>

<p>指定的覆盖值通常是文字值，它们不会被转换成bean的引用。这个约定也适用于当XML中的bean定义的原始值指定了bean引用时。</p>
<p>使用Spring 2.5中引入的<code>context</code>命名空间，可以使用专用配置元素配置属性覆盖，如以下示例所示：</p>
<pre><code>&lt;context:property-override location=&quot;classpath:override.properties&quot;/&gt;</code></pre><p><a id="beans-factory-extension-factorybean"></a></p>
<h4 id="1-8-3-使用FactoryBean自定义初始化逻辑"><a href="#1-8-3-使用FactoryBean自定义初始化逻辑" class="headerlink" title="1.8.3. 使用FactoryBean自定义初始化逻辑"></a><a href="#beans-factory-extension-factorybean"></a>1.8.3. 使用<code>FactoryBean</code>自定义初始化逻辑</h4><p>为自己工厂的对象实现<code>org.springframework.beans.factory.FactoryBean</code>接口。</p>
<p><code>FactoryBean</code>接口就是Spring IoC容器实例化逻辑的可插拔点，如果你的初始化代码非常复杂，那么相对于（潜在地）大量详细的XML而言，最好是使用Java语言来表达。 你可以创建自定义的<code>FactoryBean</code>，在该类中编写复杂的初始化代码。然后将自定义的<code>FactoryBean</code>插入到容器中。</p>
<p><code>FactoryBean</code>接口提供下面三个方法</p>
<ul>
<li><p><code>Object getObject()</code>: 返回这个工厂创建的对象实例。这个实例可能是共享的，这取决于这个工厂返回的是单例还是原型实例。</p>
</li>
<li><p><code>boolean isSingleton()</code>: 如果<code>FactoryBean</code>返回单例，那么这个方法就返回<code>true</code>，否则返回<code>false</code>。</p>
</li>
<li><p><code>Class getObjectType()</code>: 返回由<code>getObject()</code>方法返回的对象类型，如果事先不知道的类型则会返回null。</p>
</li>
</ul>
<p>Spring框架大量地使用了<code>FactoryBean</code> 的概念和接口，<code>FactoryBean</code> 接口的50多个实现都随着Spring一同提供。</p>
<p>当开发者需要向容器请求一个真实的<code>FactoryBean</code>实例（而不是它生产的bean）时，调用 <code>ApplicationContext</code>的<code>getBean()</code>方法时在bean的id之前需要添加连字符（&amp;） 所以对于一个给定id为myBean的<code>FactoryBean</code>，调用容器的<code>getBean(&quot;myBean&quot;)</code>方法返回的是FactoryBean的代理，而调用<code>getBean(&quot;&amp;myBean&quot;)</code>方法则返回FactoryBean实例本身</p>
<p><a id="beans-annotation-config"></a></p>
<h3 id="1-9-基于注解的容器配置"><a href="#1-9-基于注解的容器配置" class="headerlink" title="1.9. 基于注解的容器配置"></a><a href="#beans-annotation-config"></a>1.9. 基于注解的容器配置</h3><p>注解是否比配置Spring的XML更好?</p>
<p>在引入基于注解的配置之后,引发了这种方法是否比XML更优秀的问题.简短的答案是得看情况,每种方法都有其优缺点。通常由开发人员决定使用更适合他们的策略。 首先看看两种定义方式,注解在它们的声明中提供了很多上下文信息，使得配置变得更短、更简洁；但是，XML擅长于在不接触源码或者无需反编译的情况下装配组件，一些开发人员更喜欢在源码上使用注解配置。 而另一些人认为注解类不再是POJO，同时认为注解配置会很分散，最终难以控制。</p>
<p>无论选择如何，Spring都可以兼顾两种风格，甚至可以将它们混合在一起。Spring通过其<a href="#beans-java">JavaConfig</a> 选项，允许注解以无侵入的方式使用，即无需接触目标组件源代码。 而且在工具应用方面， <a href="https://spring.io/tools/sts" target="_blank" rel="noopener">Spring Tool Suite</a>支持所有配置形式。</p>
<p>XML设置的替代方法是基于注解的配置，它依赖于字节码元数据来连接组件进而替代XML声明。开发人员通过使用相关类、方法或字段声明上的注解来将配置移动到组件类本身。而不是使用XML bean来配置。 如示例中所述，<a href="#beans-factory-extension-bpp-examples-rabpp"><code>RequiredAnnotationBeanPostProcessor</code></a>,将<code>BeanPostProcessor</code> 与注解混合使用是扩展Spring IoC容器的常用方法。 例如，Spring 2.0引入了使用<a href="#beans-required-annotation"><code>@Required</code></a>注解强制属性必须在配置的时候被填充， Spring 2.5使用同样的方式来驱动Spring的依赖注入。本质上，<code>@Autowired</code>注解提供的功能与<a href="#beans-factory-autowire">自动装配协作</a>中描述的相同，但具有更细粒度的控制和更广泛的适用性。 Spring 2.5还增加了对JSR-250注解的支持，例如<code>@PostConstruct</code>和<code>@PreDestroy</code>。 Spring 3.0增加了对<code>javax.inject</code>包中包含的JSR-330（Java的依赖注入）注解的支持， 例如<code>@Inject</code>和<code>@Named</code>。有关这些注解的详细信息，请参阅<a href="#beans-standard-annotations">相关章节</a>。</p>
<p>注解注入在XML注入之前执行，因此同时使用这两种方式进行注入时，XML配置会覆盖注解配置。</p>
<p>与之前一样，你可以将它们注册为单独的bean定义，但也可以通过在基于XML的Spring配置中包含以下标记来隐式注册它们（请注意包含<code>context</code>命名空间）：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context/spring-context.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:annotation-config</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>（隐式注册的后处理器包括 <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.html" target="_blank" rel="noopener"><code>AutowiredAnnotationBeanPostProcessor</code></a>, <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.html" target="_blank" rel="noopener"><code>CommonAnnotationBeanPostProcessor</code></a>, <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.html" target="_blank" rel="noopener"><code>PersistenceAnnotationBeanPostProcessor</code></a>, 和前面提到的 <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.html" target="_blank" rel="noopener"><code>RequiredAnnotationBeanPostProcessor</code></a>.)</p>
<p><code>&lt;context:annotation-config/&gt;</code>只有在定义bean的相同应用程序上下文中查找bean上的注解。 这意味着，如果将 <code>&lt;context:annotation-config/&gt;</code> 放在<code>DispatcherServlet</code>的<code>WebApplicationContext</code>中， 它只检查控制器中的<code>@Autowired</code> bean，而不检查您的服务。 有关更多信息，请参阅 <a href="https://github.com/DocsHome/spring-docs/blob/master/pages/web/web.md#mvc-servlet" target="_blank" rel="noopener">DispatcherServlet</a>。</p>
<p><a id="beans-required-annotation"></a></p>
<h4 id="1-9-1-Required"><a href="#1-9-1-Required" class="headerlink" title="1.9.1. @Required"></a><a href="#beans-required-annotation"></a>1.9.1. @Required</h4><p><code>@Required</code>注解适用于bean属性setter方法，如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Required</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此注解仅表示受影响的bean属性必须在配置时通过bean定义中的显式赋值或自动注入值。如果受影响的bean属性尚未指定值，容器将抛出异常；这导致及时的、明确的失败，避免在运行后再抛出<code>NullPointerException</code>或类似的异常。 在这里，建议开发者将断言放入bean类本身，例如放入init方法。这样做强制执行那些必需的引用和值，即使是在容器外使用这个类。</p>
<p><a id="beans-autowired-annotation"></a></p>
<h4 id="1-9-2-Autowired"><a href="#1-9-2-Autowired" class="headerlink" title="1.9.2. @Autowired"></a><a href="#beans-autowired-annotation"></a>1.9.2. <code>@Autowired</code></h4><p>可以使用JSR 330的 <code>@Inject</code>注解代替本节中包含的示例中的Spring的<code>@Autowired</code>注解。 有关详细信息，<a href="#beans-standard-annotations">请参见此处</a></p>
<p>开发者可以在构造器上使用<code>@Autowired</code>注解:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> CustomerPreferenceDao customerPreferenceDao;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MovieRecommender</span><span class="params">(CustomerPreferenceDao customerPreferenceDao)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.customerPreferenceDao = customerPreferenceDao;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>从Spring Framework 4.3开始，如果目标bean仅定义一个构造函数，则不再需要<code>@Autowired</code>构造函数。如果有多个构造函数可用，则至少有一个必须注解<code>@Autowired</code>以让容器知道它使用的是哪个</p>
<p>您还可以将<code>@Autowired</code>注解应用于“传统”setter方法，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>您还可以将注解应用于具有任意名称和多个参数的方法，如以下示例所示：:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieCatalog movieCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> CustomerPreferenceDao customerPreferenceDao;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">prepare</span><span class="params">(MovieCatalog movieCatalog,</span></span></span><br><span class="line"><span class="function"><span class="params">            CustomerPreferenceDao customerPreferenceDao)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieCatalog = movieCatalog;</span><br><span class="line">        <span class="keyword">this</span>.customerPreferenceDao = customerPreferenceDao;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>还可以将<code>@Autowired</code>应用于字段，甚至可以和构造函数混合使用:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> CustomerPreferenceDao customerPreferenceDao;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MovieCatalog movieCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MovieRecommender</span><span class="params">(CustomerPreferenceDao customerPreferenceDao)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.customerPreferenceDao = customerPreferenceDao;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>确保您的组件（例如，<code>MovieCatalog</code>或<code>CustomerPreferenceDao</code>）始终按照用于@Autowired注入点的类型声明。 否则，由于在运行时未找到类型匹配，注入可能会失败。</p>
<p>对于通过类路径扫描找到的XML定义的bean或组件类，容器通常预先知道具体类型。 但是，对于<code>@Bean</code>工厂方法，您需要确保其声明的具体返回类型。 对于实现多个接口的组件或可能由其实现类型引用的组件，请考虑在工厂方法上声明最具体的返回类型（至少与引用bean的注入点所需的特定类型一致）。 .</p>
<p>也可以用在数组上，注解用于标注属性或方法，数组的类型是<code>ApplicationContext</code>中定义的bean类型。如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MovieCatalog[] movieCatalogs;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>也可以应用于集合类型，如以下示例所示:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Set&lt;MovieCatalog&gt; movieCatalogs;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieCatalogs</span><span class="params">(Set&lt;MovieCatalog&gt; movieCatalogs)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieCatalogs = movieCatalogs;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果想让数组元素或集合元素按特定顺序排列，应用的bean可以实现<code>org.springframework.core.Ordered</code>， 或者使用<code>@Order</code>或标准的@<code>@Priority</code> 注解，否则，它们的顺序遵循容器中相应目标bean定义的注册顺序。</p>
<p>您可以在类级别和<code>@Bean</code>方法上声明 <code>@Order</code>注解，可能是通过单个bean定义（在多个定义使用相同bean类的情况下）。 <code>@Order</code>值可能会影响注入点的优先级，但要注意它们不会影响单例启动顺序，这是由依赖关系和<code>@DependsOn</code>声明确定的。</p>
<p>请注意，标准的<code>javax.annotation.Priority</code>注解在<code>@Bean</code>级别不可用，因为它无法在方法上声明。 它的语义可以通过<code>@Order</code>值与<code>@Primary</code>定义每个类型的单个bean上。</p>
<p>只要键类型是<code>String</code>，<code>Map</code>类型就可以自动注入。 Map值将包含所有类型的bean，并且键将包含相应的bean名称。如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Map&lt;String, MovieCatalog&gt; movieCatalogs;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieCatalogs</span><span class="params">(Map&lt;String, MovieCatalog&gt; movieCatalogs)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieCatalogs = movieCatalogs;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>默认情况下，当没有候选的bean可用时，自动注入将会失败；默认的处理方式是将带有注解的方法，、构造函数和字段标明为required=false属性。这种设置不是必须的，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span>(required = <span class="keyword">false</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>只有一个带注解的构造函数per-class 可以标记为required，但是可以注解多个非必需的构造函数。在这种情况下，每个项都会是候选者，而Spring使用的是最贪婪的构造函数。 这个构造函数的依赖关系可以得到满足，那就是具有最多参数的构造函数。</p>
<p>推荐使用<code>@Required</code>注解来代替<code>@Autowired</code>的required属性，required属性表示该属性不是自动装配必需的，如果该属性不能被自动装配。 则该属性会被忽略。 另一方面， <code>@Required</code>会强调通过容器支持的任何方式来设置属性。 如果没有值被注入的话，会引发相应的异常。</p>
<p>或者，您可以通过Java 8的<code>java.util.Optional</code>表达特定依赖项的非必需特性，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(Optional&lt;MovieFinder&gt; movieFinder)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>从Spring Framework 5.0开始，您还可以使用<code>@Nullable</code> 注解（任何包中的任何类型，例如，来自JSR-305的 <code>javax.annotation.Nullable</code>）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(@Nullable MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>您也可以使用<code>@Autowired</code>作为常见的可解析依赖关系的接口，<code>BeanFactory</code>, <code>ApplicationContext</code>, <code>Environment</code>, <code>ResourceLoader</code>, <code>ApplicationEventPublisher</code>, 和 <code>MessageSource</code> 这些接口及其扩展接口（例如<code>ConfigurableApplicationContext</code> 或 <code>ResourcePatternResolver</code>） 会自动解析，无需特殊设置。 以下示例自动装配<code>ApplicationContext</code>对象：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> ApplicationContext context;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MovieRecommender</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>@Autowired</code>, <code>@Inject</code>, <code>@Resource</code>, 和 <code>@Value</code> 注解 由 Spring <code>BeanPostProcessor</code> 实现.也就是说开发者不能使用自定义的<code>BeanPostProcessor</code>或者自定义<code>BeanFactoryPostProcessor</code>r来使用这些注解 必须使用XML或Spring @Bean方法显式地“连接”这些类型。</p>
<p><a id="beans-autowired-annotation-primary"></a></p>
<h4 id="1-9-3-Primary"><a href="#1-9-3-Primary" class="headerlink" title="1.9.3. @Primary"></a><a href="#beans-autowired-annotation-primary"></a>1.9.3. <code>@Primary</code></h4><p>由于按类型的自动注入可能匹配到多个候选者，所以通常需要对选择过程添加更多的约束。使用Spring的<code>@Primary</code>注解是实现这个约束的一种方法。 它表示如果存在多个候选者且另一个bean只需要一个特定类型的bean依赖时，就明确使用标记有<code>@Primary</code>注解的那个依赖。如果候选中只有一个”Primary” bean，那么它就是自动注入的值</p>
<p>请考虑以下配置，将<code>firstMovieCatalog</code>定义为主要<code>MovieCatalog</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@Primary</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MovieCatalog <span class="title">firstMovieCatalog</span><span class="params">()</span> </span>&#123; ... &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MovieCatalog <span class="title">secondMovieCatalog</span><span class="params">()</span> </span>&#123; ... &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用上述配置，以下 <code>MovieRecommender</code>将与<code>firstMovieCatalog</code>一起自动装配：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MovieCatalog movieCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>相应的bean定义如下:</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=<span class="string">"1.0"</span> encoding=<span class="string">"UTF-8"</span>?&gt;</span><br><span class="line">&lt;beans xmlns=<span class="string">"http://www.springframework.org/schema/beans"</span></span><br><span class="line">    xmlns:xsi=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line">    xmlns:context=<span class="string">"http://www.springframework.org/schema/context"</span></span><br><span class="line">    xsi:schemaLocation=<span class="string">"http://www.springframework.org/schema/beans</span></span><br><span class="line"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span><br><span class="line"><span class="string">        http://www.springframework.org/schema/context</span></span><br><span class="line"><span class="string">        http://www.springframework.org/schema/context/spring-context.xsd"</span>&gt;</span><br><span class="line"></span><br><span class="line">    &lt;context:annotation-config/&gt;</span><br><span class="line"></span><br><span class="line">    &lt;bean <span class="class"><span class="keyword">class</span></span>=<span class="string">"example.SimpleMovieCatalog"</span> primary=<span class="string">"true"</span>&gt;</span><br><span class="line">        &lt;!-- inject any dependencies required by <span class="keyword">this</span> bean --&gt;</span><br><span class="line">    &lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">    &lt;bean <span class="class"><span class="keyword">class</span></span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span><br><span class="line">        &lt;!-- inject any dependencies required by <span class="keyword">this</span> bean --&gt;</span><br><span class="line">    &lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">    &lt;bean id=<span class="string">"movieRecommender"</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">"example.MovieRecommender"</span>/&gt;</span><br><span class="line"></span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure>

<p><a id="beans-autowired-annotation-qualifiers"></a></p>
<h4 id="1-9-4-使用qualifiers微调基于注解的自动装配"><a href="#1-9-4-使用qualifiers微调基于注解的自动装配" class="headerlink" title="1.9.4. 使用qualifiers微调基于注解的自动装配"></a><a href="#beans-autowired-annotation-qualifiers"></a>1.9.4. 使用qualifiers微调基于注解的自动装配</h4><p><code>@Primary</code> 是一种用于解决自动装配多个值的注入的有效的方法，当需要对选择过程做更多的约束时，可以使用Spring的<code>@Qualifier</code>注解，可以为指定的参数绑定限定的值。 缩小类型匹配集，以便为每个参数选择特定的bean。 在最简单的情况下，这可以是一个简单的描述性值，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="meta">@Qualifier</span>(<span class="string">"main"</span>)</span><br><span class="line">    <span class="keyword">private</span> MovieCatalog movieCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>您还可以在各个构造函数参数或方法参数上指定<code>@Qualifier</code>注解，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieCatalog movieCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> CustomerPreferenceDao customerPreferenceDao;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">prepare</span><span class="params">(@Qualifier(<span class="string">"main"</span>)</span>MovieCatalog movieCatalog,</span></span><br><span class="line"><span class="function">            CustomerPreferenceDao customerPreferenceDao) </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieCatalog = movieCatalog;</span><br><span class="line">        <span class="keyword">this</span>.customerPreferenceDao = customerPreferenceDao;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以下示例显示了相应的bean定义。.</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context/spring-context.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:annotation-config</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">qualifier</span> <span class="attr">value</span>=<span class="string">"main"</span>/&gt;</span> (1)</span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- inject any dependencies required by this bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">qualifier</span> <span class="attr">value</span>=<span class="string">"action"</span>/&gt;</span> (2)</span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- inject any dependencies required by this bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"movieRecommender"</span> <span class="attr">class</span>=<span class="string">"example.MovieRecommender"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>1</strong>、带有限定符”<code>main</code>“的bean会被装配到拥有相同值的构造方法参数上.</p>
<p><strong>2</strong>、带有限定符”<code>action</code>“的bean会被装配到拥有相同值的构造方法参数上.</p>
<p>bean的name会作为备用的qualifier值,因此可以定义bean的<code>id</code>为 main 替代内嵌的qualifier元素.这种匹配方式同样有效。但是，虽然可以使用这个约定来按名称引用特定的bean， 但是<code>@Autowired</code>默认是由带限定符的类型驱动注入的。这就意味着qualifier值，甚至是bean的name作为备选项，只是为了缩小类型匹配的范围。它们在语义上不表示对唯一bean id的引用。 良好的限定符值是像<code>main</code> 或 <code>EMEA</code> 或 <code>persistent</code>这样的，能表示与bean id无关的特定组件的特征，在匿名bean定义的情况下可以自动生成。</p>
<p>Qualifiers也可以用于集合类型，如上所述，例如 <code>Set&lt;MovieCatalog&gt;</code>。在这种情况下，根据声明的限定符，所有匹配的bean都作为集合注入。 这意味着限定符不必是唯一的。 相反，它们构成过滤标准。 例如，您可以使用相同的限定符值“action”定义多个<code>MovieCatalog</code> bean，所有这些bean都注入到使用<code>@Qualifier(&quot;action&quot;)</code>注解的<code>Set&lt;MovieCatalog&gt;</code>中。</p>
<p>在类型匹配候选项中，根据目标bean名称选择限定符值，在注入点不需要<code>@Qualifier</code>注解。 如果没有其他解析指示符（例如限定符或主标记）， 则对于非唯一依赖性情况，Spring会将注入点名称（即字段名称或参数名称）与目标bean名称进行匹配，然后选择同名的候选者，如果有的话。</p>
<p>如果打算by name来驱动注解注入，那么就不要使用<code>@Autowired</code>（多数情况），即使在技术上能够通过@Qualifier值引用bean名字。相反，应该使用JSR-250 <code>@Resource</code> 注解，该注解在语义上定义为通过其唯一名称标识特定目标组件，其中声明的类型与匹配进程无关。<code>@Autowired</code>具有多种不同的语义，在by type选择候选bean之后，指定的<code>String</code>限定的值只会考虑这些被选择的候选者。 例如将<code>account</code> 限定符与标有相同限定符标签的bean相匹配。</p>
<p>对于自身定义为 collection, <code>Map</code>, 或者 array type的bean， <code>@Resource</code>是一个很好的解决方案，通过唯一名称引用特定的集合或数组bean。 也就是说，从Spring4.3开始，只要元素类型信息保存在 <code>@Bean</code> 返回类型签名或集合（或其子类）中，您就可以通过Spring的 <code>@Autowired</code>类型匹配算法匹配Map和数组类型。 在这种情况下，可以使用限定的值来选择相同类型的集合，如上一段所述。</p>
<p>从Spring4.3开始，<code>@Autowired</code>也考虑了注入的自引用，即引用当前注入的bean。自引用只是一种后备选项，还是优先使用正常的依赖注入操作其它bean。 在这个意义上，自引用不参与到正常的候选者选择中，并且总是次要的，，相反，它们总是拥有最低的优先级。在实践中，自引用通常被用作最后的手段。例如，通过bean的事务代理在同一实例上调用其他方法 在这种情况下，考虑将受影响的方法分解为单独委托的bean，或者使用 <code>@Resource</code>,，它可以通过其唯一名称获取代理返回到当前的bean上。</p>
<p><code>@Autowired</code>可以应用在字段、构造函数和多参数方法上，允许在参数上使用qualifier限定符注解缩小取值范围。相比之下，<code>@Resource</code>仅支持具有单个参数的字段和bean属性setter方法。 因此，如果注入目标是构造函数或多参数方法，请使用qualifiers限定符。</p>
<p>开发者也可以创建自定义的限定符注解，只需定义一个注解，在其上提供了@Qualifier注解即可。如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.FIELD, ElementType.PARAMETER&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Qualifier</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Genre &#123;</span><br><span class="line"></span><br><span class="line">    <span class="function">String <span class="title">value</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后，您可以在自动装配的字段和参数上提供自定义限定符，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="meta">@Genre</span>(<span class="string">"Action"</span>)</span><br><span class="line">    <span class="keyword">private</span> MovieCatalog actionCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieCatalog comedyCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setComedyCatalog</span><span class="params">(@Genre(<span class="string">"Comedy"</span>)</span> MovieCatalog comedyCatalog) </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.comedyCatalog = comedyCatalog;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接下来，提供候选bean定义的信息。开发者可以添加<code>&lt;qualifier/&gt;</code>标签作为<code>&lt;bean/&gt;</code>标签的子元素，然后指定 <code>type</code>类型和<code>value</code>值来匹配自定义的qualifier注解。 type是自定义注解的权限定类名(包路径+类名）。如果没有重名的注解，那么可以使用类名(不含包路径）。 以下示例演示了两种方法：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context/spring-context.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:annotation-config</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">qualifier</span> <span class="attr">type</span>=<span class="string">"Genre"</span> <span class="attr">value</span>=<span class="string">"Action"</span>/&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- inject any dependencies required by this bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">qualifier</span> <span class="attr">type</span>=<span class="string">"example.Genre"</span> <span class="attr">value</span>=<span class="string">"Comedy"</span>/&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- inject any dependencies required by this bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"movieRecommender"</span> <span class="attr">class</span>=<span class="string">"example.MovieRecommender"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在 <a href="#beans-classpath-scanning">类路径扫描和组件管理</a>,将展示一个基于注解的替代方法，可以在XML中提供qualifier元数据, 请参阅<a href="#beans-scanning-qualifiers">使用注解提供限定符元数据。</a></p>
<p>在某些情况下，使用没有值的注解可能就足够了。当注解用于更通用的目的并且可以应用在多种不同类型的依赖上时，这是很有用的。 例如，您可以提供可在没有Internet连接时搜索的Offline目录。 首先，定义简单注解，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.FIELD, ElementType.PARAMETER&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Qualifier</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Offline &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后将注解添加到需要自动注入的字段或属性中:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="meta">@Offline</span> (<span class="number">1</span>)</span><br><span class="line">    <span class="keyword">private</span> MovieCatalog offlineCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1</strong>、此行添加<code>@Offline</code>注解</p>
<p>现在bean定义只需要一个限定符类型，如下例所示：:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">qualifier</span> <span class="attr">type</span>=<span class="string">"Offline"</span>/&gt;</span> (1)</span><br><span class="line">    <span class="comment">&lt;!-- inject any dependencies required by this bean --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>1</strong>、此元素指定限定符。</p>
<p>开发者还可以为自定义限定名qualifier注解增加属性，用于替代简单的<code>value</code>属性。如果在要自动注入的字段或参数上指定了多个属性值，则bean的定义必须全部匹配这些属性值才能被视为自动注入候选者。 例如，请考虑以下注解定义：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.FIELD, ElementType.PARAMETER&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Qualifier</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> MovieQualifier &#123;</span><br><span class="line"></span><br><span class="line">    <span class="function">String <span class="title">genre</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">Format <span class="title">format</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这种情况下， <code>Format</code>是一个枚举类型，定义如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> Format &#123;</span><br><span class="line">    VHS, DVD, BLURAY</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>要自动装配的字段使用自定义限定符进行注解，并包含两个属性的值：<code>genre</code> 和 <code>format</code>，如以下示例所示:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="meta">@MovieQualifier</span>(format=Format.VHS, genre=<span class="string">"Action"</span>)</span><br><span class="line">    <span class="keyword">private</span> MovieCatalog actionVhsCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="meta">@MovieQualifier</span>(format=Format.VHS, genre=<span class="string">"Comedy"</span>)</span><br><span class="line">    <span class="keyword">private</span> MovieCatalog comedyVhsCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="meta">@MovieQualifier</span>(format=Format.DVD, genre=<span class="string">"Action"</span>)</span><br><span class="line">    <span class="keyword">private</span> MovieCatalog actionDvdCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="meta">@MovieQualifier</span>(format=Format.BLURAY, genre=<span class="string">"Comedy"</span>)</span><br><span class="line">    <span class="keyword">private</span> MovieCatalog comedyBluRayCatalog;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后，bean定义应包含匹配的限定符值。此示例还演示了可以使用bean meta属性而不是使用<code>&lt;qualifier/&gt;</code>子元素。如果可行，<code>&lt;qualifier/&gt;</code>元素及其属性优先， 但如果不存在此类限定符，那么自动注入机制会使用 <code>&lt;meta/&gt;</code> 标签中提供的值，如以下示例中的最后两个bean定义：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context/spring-context.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:annotation-config</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">qualifier</span> <span class="attr">type</span>=<span class="string">"MovieQualifier"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">attribute</span> <span class="attr">key</span>=<span class="string">"format"</span> <span class="attr">value</span>=<span class="string">"VHS"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">attribute</span> <span class="attr">key</span>=<span class="string">"genre"</span> <span class="attr">value</span>=<span class="string">"Action"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">qualifier</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- inject any dependencies required by this bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">qualifier</span> <span class="attr">type</span>=<span class="string">"MovieQualifier"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">attribute</span> <span class="attr">key</span>=<span class="string">"format"</span> <span class="attr">value</span>=<span class="string">"VHS"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">attribute</span> <span class="attr">key</span>=<span class="string">"genre"</span> <span class="attr">value</span>=<span class="string">"Comedy"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">qualifier</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- inject any dependencies required by this bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">key</span>=<span class="string">"format"</span> <span class="attr">value</span>=<span class="string">"DVD"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">key</span>=<span class="string">"genre"</span> <span class="attr">value</span>=<span class="string">"Action"</span>/&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- inject any dependencies required by this bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"example.SimpleMovieCatalog"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">key</span>=<span class="string">"format"</span> <span class="attr">value</span>=<span class="string">"BLURAY"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">key</span>=<span class="string">"genre"</span> <span class="attr">value</span>=<span class="string">"Comedy"</span>/&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- inject any dependencies required by this bean --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><a id="beans-generics-as-qualifiers"></a></p>
<h4 id="1-9-5-使用泛型作为自动装配限定符"><a href="#1-9-5-使用泛型作为自动装配限定符" class="headerlink" title="1.9.5. 使用泛型作为自动装配限定符"></a><a href="#beans-generics-as-qualifiers"></a>1.9.5. 使用泛型作为自动装配限定符</h4><p>除了<code>@Qualifier</code> 注解之外，您还可以使用Java泛型类型作为隐式的限定形式。 例如，假设您具有以下配置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> StringStore <span class="title">stringStore</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> StringStore();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> IntegerStore <span class="title">integerStore</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> IntegerStore();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>假设上面的bean都实现了泛型接口,即 <code>Store&lt;String&gt;</code>和<code>Store&lt;Integer&gt;</code>,那么可以用<code>@Autowire</code>来注解<code>Store</code> 接口, 并将泛型用作限定符，如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> Store&lt;String&gt; s1; <span class="comment">// &lt;String&gt; qualifier, injects the stringStore bean</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> Store&lt;Integer&gt; s2; <span class="comment">// &lt;Integer&gt; qualifier, injects the integerStore bean</span></span><br></pre></td></tr></table></figure>

<p>通用限定符也适用于自动装配列表，<code>Map</code>实例和数组。 以下示例自动装配通用<code>List</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Inject all Store beans as long as they have an &lt;Integer&gt; generic</span></span><br><span class="line"><span class="comment">// Store&lt;String&gt; beans will not appear in this list</span></span><br><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> List&lt;Store&lt;Integer&gt;&gt; s;</span><br></pre></td></tr></table></figure>

<p><a id="beans-custom-autowire-configurer"></a></p>
<h4 id="1-9-6-CustomAutowireConfigurer"><a href="#1-9-6-CustomAutowireConfigurer" class="headerlink" title="1.9.6. CustomAutowireConfigurer"></a><a href="#beans-custom-autowire-configurer"></a>1.9.6. <code>CustomAutowireConfigurer</code></h4><p><a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/annotation/CustomAutowireConfigurer.html" target="_blank" rel="noopener"><code>CustomAutowireConfigurer</code></a> 是一个<code>BeanFactoryPostProcessor</code>，它允许开发者注册自定义的qualifier注解类型，而无需指定<code>@Qualifier</code>注解，以下示例显示如何使用<code>CustomAutowireConfigurer</code>:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"customAutowireConfigurer"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">"org.springframework.beans.factory.annotation.CustomAutowireConfigurer"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"customQualifierTypes"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">set</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>example.CustomQualifier<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>AutowireCandidateResolver</code> 通过以下方式确定自动注入的候选者:</p>
<ul>
<li><p>每个bean定义的<code>autowire-candidate</code>值</p>
</li>
<li><p>在<code>&lt;beans/&gt;</code>元素上使用任何可用的 <code>default-autowire-candidates</code> 模式</p>
</li>
<li><p>存在 <code>@Qualifier</code> 注解以及使用<code>CustomAutowireConfigurer</code>注册的任何自定义注解</p>
</li>
</ul>
<p>当多个bean有资格作为自动注入的候选项时，“primary”的确定如下：如果候选者中只有一个bean定义的 <code>primary</code>属性设置为<code>true</code>，则选择它。</p>
<p><a id="beans-resource-annotation"></a></p>
<h4 id="1-9-7-Resource"><a href="#1-9-7-Resource" class="headerlink" title="1.9.7. @Resource"></a><a href="#beans-resource-annotation"></a>1.9.7. <code>@Resource</code></h4><p>Spring还通过在字段或bean属性setter方法上使用JSR-250 <code>@Resource</code>注解来支持注入。 这是Java EE 5和6中的常见模式（例如，在JSF 1.2托管bean或JAX-WS 2.0端点中）。 Spring也为Spring管理对象提供这种模式。</p>
<p><code>@Resource</code> 接受一个name属性.。默认情况下，Spring将该值解释为要注入的bean名称。 换句话说，它遵循按名称语义，如以下示例所示:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span>(name=<span class="string">"myMovieFinder"</span>) (<span class="number">1</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1</strong>、这行注入一个<code>@Resource</code>.</p>
<p>如果未明确指定名称，则默认名称是从字段名称或setter方法派生的。 如果是字段，则采用字段名称。 在setter方法的情况下，它采用bean属性名称。 下面的例子将把名为<code>movieFinder</code>的bean注入其setter方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>ApplicationContext</code>若使用了<code>CommonAnnotationBeanPostProcessor</code>，注解提供的name名字将被解析为bean的name名字。 如果配置了Spring的 <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/jndi/support/SimpleJndiBeanFactory.html" target="_blank" rel="noopener"><code>SimpleJndiBeanFactory</code></a>，这些name名称就可以通过JNDI解析。但是，推荐使用默认的配置，简单地使用Spring的JNDI，这样可以保持逻辑引用。而不是直接引用。</p>
<p>@Resource在没有明确指定name时，其行为类似于<code>@Autowired</code>，对于特定bean(Spring API内的bean）， <code>@Resource</code> 找到主要类型匹配而不是特定的命名bean， 并解析众所周知的可解析依赖项：<code>ApplicationContext</code>, <code>ResourceLoader</code>, <code>ApplicationEventPublisher</code>, 和 <code>MessageSource</code>接口。</p>
<p>因此，在以下示例中，<code>customerPreferenceDao</code>字段首先查找名为customerPreferenceDao的bean，如果未找到，则会使用类型匹配<code>CustomerPreferenceDao</code>类的实例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieRecommender</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> CustomerPreferenceDao customerPreferenceDao;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> ApplicationContext context; (<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MovieRecommender</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1</strong>、<code>context</code>域将会注入<code>ApplicationContext</code></p>
<p><a id="beans-postconstruct-and-predestroy-annotations"></a></p>
<h4 id="1-9-8-PostConstruct-和-PreDestroy"><a href="#1-9-8-PostConstruct-和-PreDestroy" class="headerlink" title="1.9.8. @PostConstruct 和 @PreDestroy"></a><a href="#beans-postconstruct-and-predestroy-annotations"></a>1.9.8. <code>@PostConstruct</code> 和 <code>@PreDestroy</code></h4><p><code>CommonAnnotationBeanPostProcessor</code> 不仅仅识别<code>@Resource</code> 注解，还识别JSR-250生命周期注解。，在Spring 2.5中引入了这些注解， 它们提供了另一个替代<a href="#beans-factory-lifecycle-initializingbean">初始化回调</a>和<a href="#beans-factory-lifecycle-disposablebean">销毁回调</a>。 如果<code>CommonAnnotationBeanPostProcessor</code>在Spring <code>ApplicationContext</code>中注册，它会在相应的Spring bean生命周期中调用相应的方法，就像是Spring生命周期接口方法，或者是明确声明的回调函数那样。 在以下示例中，缓存在初始化时预先填充并在销毁时清除：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CachingMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostConstruct</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">populateMovieCache</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// populates the movie cache upon initialization...</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PreDestroy</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clearMovieCache</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// clears the movie cache upon destruction...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>有关组合各种生命周期机制的影响的详细信息，请参阅组合<a href="#beans-factory-lifecycle-combined-effects">生命周期机制</a>。</p>
<p><a id="beans-classpath-scanning"></a></p>
<h3 id="1-10-类路径扫描和管理组件"><a href="#1-10-类路径扫描和管理组件" class="headerlink" title="1.10. 类路径扫描和管理组件"></a><a href="#beans-classpath-scanning"></a>1.10. 类路径扫描和管理组件</h3><p>本章中的大多数示例会使用XML配置指定在Spring容器中生成每个<code>BeanDefinition</code>的元数据，上一节（<a href="#beans-annotation-config">基于注解的容器配置</a>）演示了如何通过源代码注解提供大量的元数据配置。 然而，即使在这些示例中，注解也仅仅用于驱动依赖注入。 “base” bean依然会显式地在XML文件中定义。本节介绍通过扫描类路径隐式检测候选组件的选项。候选者组件是class类， 这些类经过过滤匹配，由Spring容器注册的bean定义会成为Spring bean。这消除了使用XML执行bean注册的需要(也就是没有XML什么事儿了),可以使用注解(例如<code>@Component</code>)， AspectJ类型表达式或开发者自定义过滤条件来选择哪些类将在容器中注册bean定义。</p>
<p>从Spring 3.0开始，Spring JavaConfig项目提供的许多功能都是核心Spring 框架的一部分。这允许开发者使用Java而不是使用传统的XML文件来定义bean。 有关如何使用这些新功能的示例，请查看<code>@Configuration</code>, <code>@Bean</code>,<code>@Import</code>, 和 <code>@DependsOn</code>注解。</p>
<p><a id="beans-stereotype-annotations"></a></p>
<h4 id="1-10-1-Component注解和更多模板注解"><a href="#1-10-1-Component注解和更多模板注解" class="headerlink" title="1.10.1. @Component注解和更多模板注解"></a><a href="#beans-stereotype-annotations"></a>1.10.1. <code>@Component</code>注解和更多模板注解</h4><p><code>@Repository</code>注解用于满足存储库(也称为数据访问对象或DAO)的情况,这个注解的用途是自动转换异常。如<a href="https://github.com/DocsHome/spring-docs/blob/master/pages/dataaccess/data-access.md#orm-exception-translation" target="_blank" rel="noopener">异常转换</a>中所述。</p>
<p>Spring提供了更多的构造型注解：<code>@Component</code>, <code>@Service</code>, 和<code>@Controller</code>. <code>@Component</code> 可用于管理任何Spring的组件。 <code>@Repository</code>, <code>@Service</code>, 或 <code>@Controller</code>是<code>@Component</code>的特殊化。用于更具体的用例（分别在持久性，服务和表示层中）。 因此，您可以使用<code>@Component</code>注解组件类，但是，通过使用<code>@Repository</code>, <code>@Service</code>, 和 <code>@Controller</code>注解它们，能够让你的类更易于被合适的工具处理或与相应的切面关联。 例如，这些注解可以使目标组件变成切入点。在Spring框架的未来版本中，<code>@Repository</code>, <code>@Service</code>, 和 <code>@Controller</code>也可能带有附加的语义。 因此，如果在使用<code>@Component</code> 或 <code>@Service</code> 来选择服务层时，@Service显然是更好的选择。同理，在持久化层要选择<code>@Repository</code>，它能自动转换异常。</p>
<p><a id="beans-meta-annotations"></a></p>
<h4 id="1-10-2-使用元注解和组合注解"><a href="#1-10-2-使用元注解和组合注解" class="headerlink" title="1.10.2. 使用元注解和组合注解"></a><a href="#beans-meta-annotations"></a>1.10.2. 使用元注解和组合注解</h4><p>Spring提供的许多注解都可以在您自己的代码中用作元注解。 元注解是可以应用于另一个注解的注解。 例如，<a href="#beans-stereotype-annotations">前面提到的</a> <code>@Service</code>注解是使用<code>@Component</code>进行元注解的，如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(ElementType.TYPE)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="meta">@Component</span> (<span class="number">1</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Service &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ....</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1</strong>、<code>Component</code>使<code>@Service</code>以与@<code>@Component</code>相同的方式处理。</p>
<p>元注解也可以进行组合，进而创建组合注解。例如，来自Spring MVC的<code>@RestController</code>注解是由<code>@Controller</code>和<code>@ResponseBody</code>组成的</p>
<p>此外，组合注解也可以重新定义来自元注解的属性。这在只想公开元注解的部分属性时非常有用。例如，Spring的<code>@SessionScope</code>注解将它的作用域硬编码为<code>session</code>，但仍允许自定义<code>proxyMode</code>。 以下清单显示了<code>SessionScope</code>注解的定义：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.TYPE, ElementType.METHOD&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="meta">@Scope</span>(WebApplicationContext.SCOPE_SESSION)</span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> SessionScope &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Alias for &#123;<span class="doctag">@link</span> Scope#proxyMode&#125;.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Defaults to &#123;<span class="doctag">@link</span> ScopedProxyMode#TARGET_CLASS&#125;.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@AliasFor</span>(annotation = Scope<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class">    <span class="title">ScopedProxyMode</span> <span class="title">proxyMode</span>() <span class="title">default</span> <span class="title">ScopedProxyMode</span>.<span class="title">TARGET_CLASS</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后，您可以使用<code>@SessionScope</code>而不声明<code>proxyMode</code>，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="meta">@SessionScope</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SessionScopedService</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>您还可以覆盖<code>proxyMode</code>的值，如以下示例所示:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="meta">@SessionScope</span>(proxyMode = ScopedProxyMode.INTERFACES)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SessionScopedUserService</span> <span class="keyword">implements</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>有关更多详细信息，请参阅<a href="https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Programming-Model" target="_blank" rel="noopener">Spring注解编程模型</a>wiki页面.</p>
<p><a id="beans-scanning-autodetection"></a></p>
<h4 id="1-10-3-自动探测类并注册bean定义"><a href="#1-10-3-自动探测类并注册bean定义" class="headerlink" title="1.10.3. 自动探测类并注册bean定义"></a><a href="#beans-scanning-autodetection"></a>1.10.3. 自动探测类并注册bean定义</h4><p>Spring可以自动检测各代码层中被注解的类，并使用<code>ApplicationContext</code>内注册相应的<code>BeanDefinition</code>。例如，以下两个类就可以被自动探测：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SimpleMovieLister</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Repository</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JpaMovieFinder</span> <span class="keyword">implements</span> <span class="title">MovieFinder</span> </span>&#123;</span><br><span class="line">    <span class="comment">// implementation elided for clarity</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>想要自动检测这些类并注册相应的bean，需要在<code>@Configuration</code>配置中添加<code>@ComponentScan</code>注解，其中<code>basePackages</code>属性是两个类的父包路径。 （或者，您可以指定以逗号或分号或空格分隔的列表，其中包含每个类的父包）。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ComponentScan</span>(basePackages = <span class="string">"org.example"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span>  </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>为简洁起见，前面的示例可能使用了注解的<code>value</code>属性（即<code>@ComponentScan(&quot;org.example&quot;)</code>）。</p>
<p>或者使用XML配置代替扫描:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:context</span>=<span class="string">"http://www.springframework.org/schema/context"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context/spring-context.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:component-scan</span> <span class="attr">base-package</span>=<span class="string">"org.example"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>使用<code>&lt;context:component-scan&gt;</code>隐式启用<code>&lt;context:annotation-config&gt;</code>的功能。 使用<code>&lt;context:component-scan&gt;</code>时，通常不需要包含<code>&lt;context:annotation-config&gt;</code>元素。</p>
<p>类路径扫描的包必须保证这些包出现在类路径中。当使用Ant构建JAR时，请确保你没有激活JAR任务的纯文件开关。此外在某些环境装由于安全策略，类路径目录可能不能访问。 JDK 1.7.0_45及更高版本上的独立应用程序（需要在清单中设置“Trusted-Library”） - 请参阅 <a href="https://stackoverflow.com/questions/19394570/java-jre-7u45-breaks-classloader-getresources" target="_blank" rel="noopener">http://stackoverflow.com/questions/19394570/java-jre-7u45-breaks-classloader-getresources</a>）。</p>
<p>在JDK 9的模块路径（Jigsaw）上，Spring的类路径扫描通常按预期工作。，但是，请确保在模块信息描述符中导出组件类。 如果您希望Spring调用类的非公共成员，请确保它们已“打开”（即，它们在<code>module-info</code>描述符中使用<code>opens</code> 声明而不是<code>exports</code>声明）。</p>
<p>在使用component-scan元素时， <code>AutowiredAnnotationBeanPostProcessor</code> 和 <code>CommonAnnotationBeanPostProcessor</code>都会隐式包含。意味着这两个组件也是自动探测和注入的。 所有这些都无需XML配置。</p>
<p>您可以通过annotation-config=false属性来禁用<code>AutowiredAnnotationBeanPostProcessor</code> 和<code>CommonAnnotationBeanPostProcessor</code>的注册。</p>
<p><a id="beans-scanning-filters"></a></p>
<h4 id="1-10-4-在自定义扫描中使用过滤器"><a href="#1-10-4-在自定义扫描中使用过滤器" class="headerlink" title="1.10.4. 在自定义扫描中使用过滤器"></a><a href="#beans-scanning-filters"></a>1.10.4. 在自定义扫描中使用过滤器</h4><p>默认情况下，使用<code>@Component</code>, <code>@Repository</code>, <code>@Service</code>,<code>@Controller</code>注解的类或者注解为<code>@Component</code>的自定义注解类才能被检测为候选组件。 但是，开发者可以通过应用自定义过滤器来修改和扩展此行为。将它们添加为<code>@ComponentScan</code>注解的<code>includeFilters</code>或<code>excludeFilters</code>参数(或作为<code>component-scan</code> 元素。元素的<code>include-filter</code>或<code>exclude-filter</code>子元素。每个filter元素都需要包含<code>type</code>和<code>expression</code>属性。下表介绍了筛选选项：</p>
<p>Table 5.过滤类型</p>
<table>
<thead>
<tr>
<th>过滤类型</th>
<th>表达式例子</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>annotation (default)</td>
<td><code>org.example.SomeAnnotation</code></td>
<td>要在目标组件中的类级别出现的注解。</td>
</tr>
<tr>
<td>assignable</td>
<td><code>org.example.SomeClass</code></td>
<td>目标组件可分配给（继承或实现）的类（或接口）。</td>
</tr>
<tr>
<td>aspectj</td>
<td><code>org.example..*Service+</code></td>
<td>要由目标组件匹配的AspectJ类型表达式。</td>
</tr>
<tr>
<td>regex</td>
<td><code>org\.example\.Default.*</code></td>
<td>要由目标组件类名匹配的正则表达式。</td>
</tr>
<tr>
<td>custom</td>
<td><code>org.example.MyTypeFilter</code></td>
<td><code>org.springframework.core.type .TypeFilter</code>接口的自定义实现。</td>
</tr>
</tbody></table>
<p>以下示例显示忽略所有<code>@Repository</code> 注解并使用“stub”存储库的配置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ComponentScan</span>(basePackages = <span class="string">"org.example"</span>,</span><br><span class="line">        includeFilters = <span class="meta">@Filter</span>(type = FilterType.REGEX, pattern = <span class="string">".*Stub.*Repository"</span>),</span><br><span class="line">        excludeFilters = <span class="meta">@Filter</span>(Repository<span class="class">.<span class="keyword">class</span>))</span></span><br><span class="line"><span class="class"><span class="title">public</span> <span class="title">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以下清单显示了等效的XML：:</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;beans&gt;</span><br><span class="line">    &lt;context:component-scan base-<span class="keyword">package</span>=<span class="string">"org.example"</span>&gt;</span><br><span class="line">        &lt;context:include-filter type=<span class="string">"regex"</span></span><br><span class="line">                expression=<span class="string">".*Stub.*Repository"</span>/&gt;</span><br><span class="line">        &lt;context:exclude-filter type=<span class="string">"annotation"</span></span><br><span class="line">                expression=<span class="string">"org.springframework.stereotype.Repository"</span>/&gt;</span><br><span class="line">    &lt;/context:component-scan&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure>

<p>你还可以通过在注解上设置<code>useDefaultFilters=false</code>或通过<code>use-default-filters=&quot;false&quot;</code>作为&lt;<code>&lt;component-scan/&gt;</code> 元素的属性来禁用默认过滤器。这样将不会自动检测带有<code>@Component</code>, <code>@Repository</code>,<code>@Service</code>, <code>@Controller</code>, 或 <code>@Configuration</code>.</p>
<p><a id="beans-factorybeans-annotations"></a></p>
<h4 id="1-10-5-在组件中定义bean的元数据"><a href="#1-10-5-在组件中定义bean的元数据" class="headerlink" title="1.10.5.在组件中定义bean的元数据"></a><a href="#beans-factorybeans-annotations"></a>1.10.5.在组件中定义bean的元数据</h4><p>Spring组件也可以向容器提供bean定义元数据，。在<code>@Configuration</code>注解的类中使用<code>@Bean</code>注解定义bean元数据(也就是Spring bean),以下示例显示了如何执行此操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FactoryMethodComponent</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@Qualifier</span>(<span class="string">"public"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> TestBean <span class="title">publicInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TestBean(<span class="string">"publicInstance"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doWork</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// Component method implementation omitted</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个类是一个Spring组件，它有个 <code>doWork()</code>方法。然而，它还有一个工厂方法 <code>publicInstance()</code>用于产生bean定义。<code>@Bean</code>注解了工厂方法， 还设置了其他bean定义的属性，例如通过<code>@Qualifier</code>注解的qualifier值。可以指定的其他方法级别的注解是 <code>@Scope</code>, <code>@Lazy</code>以及自定义的qualifier注解。</p>
<p>除了用于组件初始化的角色之外，<code>@Lazy</code>注解也可以在<code>@Autowired</code>或者code&gt;@Inject注解上，在这种情况下，该注入将会变成延迟注入代理lazy-resolution proxy（也就是懒加载）。</p>
<p>自动注入的字段和方法也可以像前面讨论的一样被支持，也支持<code>@Bean</code>方法的自动注入。以下示例显示了如何执行此操作：:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FactoryMethodComponent</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> i;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@Qualifier</span>(<span class="string">"public"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> TestBean <span class="title">publicInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TestBean(<span class="string">"publicInstance"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// use of a custom qualifier and autowiring of method parameters</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> TestBean <span class="title">protectedInstance</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            @Qualifier(<span class="string">"public"</span>)</span> TestBean spouse,</span></span><br><span class="line"><span class="function">            @<span class="title">Value</span><span class="params">(<span class="string">"#&#123;privateInstance.age&#125;"</span>)</span> String country) </span>&#123;</span><br><span class="line">        TestBean tb = <span class="keyword">new</span> TestBean(<span class="string">"protectedInstance"</span>, <span class="number">1</span>);</span><br><span class="line">        tb.setSpouse(spouse);</span><br><span class="line">        tb.setCountry(country);</span><br><span class="line">        <span class="keyword">return</span> tb;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> TestBean <span class="title">privateInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TestBean(<span class="string">"privateInstance"</span>, i++);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@RequestScope</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TestBean <span class="title">requestScopedInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TestBean(<span class="string">"requestScopedInstance"</span>, <span class="number">3</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该示例将方法参数为<code>String</code>，名称为<code>country</code>的bean自动装配为另一个名为<code>privateInstance</code>的bean的<code>age</code>属性值。 Spring表达式语言元素通过记号<code>#{ &lt;expression&gt; }</code>来定义属性的值。对于 <code>@Value</code>注解，表达式解析器在解析表达式后，会查找bean的名字并设置value值。</p>
<p>从Spring4.3开始，您还可以声明一个类型为<code>InjectionPoint</code>的工厂方法参数（或其更具体的子类：<code>DependencyDescriptor</code>）以访问触发创建当前bean的请求注入点。 请注意，这仅适用于真实创建的bean实例，而不适用于注入现有实例。因此，这个特性对prototype scope的bean最有意义。对于其他作用域，工厂方法将只能看到触发在给定scope中创建新bean实例的注入点。 例如，触发创建一个延迟单例bean的依赖。在这种情况下，使用提供的注入点元数据拥有优雅的语义。 以下示例显示了如何使用<code>InjectionPoint</code>:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FactoryMethodComponent</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span> <span class="meta">@Scope</span>(<span class="string">"prototype"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> TestBean <span class="title">prototypeInstance</span><span class="params">(InjectionPoint injectionPoint)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TestBean(<span class="string">"prototypeInstance for "</span> + injectionPoint.getMember());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在Spring组件中处理<code>@Bean</code>和在code&gt;@Configuration中处理是不一样的，区别在于，在<code>@Component</code>中，不会使用CGLIB增强去拦截方法和属性的调用。在<code>@Configuration</code>注解的类中， <code>@Bean</code>注解创建的bean对象会使用CGLIB代理对方法和属性进行调用。方法的调用不是常规的Java语法，而是通过容器来提供通用的生命周期管理和代理Spring bean， 甚至在通过编程的方式调用<code>@Bean</code>方法时也会产生对其它bean的引用。相比之下，在一个简单的<code>@Component</code>类中调用<code>@Bean</code>方法中的方法或字段具有标准Java语义，这里没有用到特殊的CGLIB处理或其他约束。</p>
<p>开发者可以将<code>@Bean</code>方法声明为<code>static</code>的，并允许在不将其包含的配置类作为实例的情况下调用它们。这在定义后置处理器bean时是特别有意义的。 例如<code>BeanFactoryPostProcessor</code> 或<code>BeanPostProcessor</code>),，因为这类bean会在容器的生命周期前期被初始化，而不会触发其它部分的配置。</p>
<p>对静态<code>@Bean</code>方法的调用永远不会被容器拦截，即使在<code>@Configuration</code>类内部。这是用为CGLIB的子类代理限制了只会重写非静态方法。因此， 对另一个<code>@Bean</code>方法的直接调用只能使用标准的Java语法。也只能从工厂方法本身直接返回一个独立的实例。</p>
<p>由于Java语言的可见性，<code>@Bean</code>方法并不一定会对容器中的bean有效。开发者可能很随意的在非<code>@Configuration</code>类中定义或定义为静态方法。然而， 在<code>@Configuration</code>类中的正常<code>@Bean</code>方法都会被重写，因此，它们不应该定义为<code>private</code>或<code>final</code>。</p>
<p><code>@Bean</code>方法也可以用在父类中，同样适用于Java 8接口中的默认方法。这使得组建复杂的配置时能具有更好的灵活性，甚至可能通过Java 8的默认方法实现多重继承。 这种特性在Spring 4.2开始支持。</p>
<p>最后，请注意，单个类可以为同一个bean保存多个<code>@Bean</code>方法，例如根据运行时可用的依赖关系选择合适的工厂方法。使用算法会选择 “最贪婪“的构造方法， 一些场景可能会按如下方法选择相应的工厂方法：满足最多依赖的会被选择，这与使用<code>@Autowired</code> 时选择多个构造方法时类似。</p>
<p><a id="beans-scanning-name-generator"></a></p>
<h4 id="1-10-6-命名自动注册组件"><a href="#1-10-6-命名自动注册组件" class="headerlink" title="1.10.6. 命名自动注册组件"></a><a href="#beans-scanning-name-generator"></a>1.10.6. 命名自动注册组件</h4><p>扫描处理过程，其中一步就是自动探测组件，扫描器使用<code>BeanNameGenerator</code>对探测到的组件命名。默认情况下，各代码层注解(<code>@Component</code>, <code>@Repository</code>, <code>@Service</code>, 和 <code>@Controller</code>)所包含的name值，将会作为相应的bean定义的名字。</p>
<p>如果这些注解没有name值，或者是其他一些被探测到的组件（比如使用自定义过滤器探测到的)，默认会又bean name生成器生成，使用小写类名作为bean名字。 例如，如果检测到以下组件类，则名称为<code>myMovieLister</code>和<code>movieFinderImpl</code>:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span>(<span class="string">"myMovieLister"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Repository</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieFinderImpl</span> <span class="keyword">implements</span> <span class="title">MovieFinder</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果您不想依赖默认的bean命名策略，则可以提供自定义bean命名策略。首先，实现 <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/beans/factory/support/BeanNameGenerator.html" target="_blank" rel="noopener"><code>BeanNameGenerator</code></a>接口，并确保包括一个默认的无参构造函数。 然后，在配置扫描程序时提供完全限定的类名，如以下示例注解和bean定义所示：</p>
<pre><code>@Configuration
@ComponentScan(basePackages = &quot;org.example&quot;, nameGenerator = MyNameGenerator.class)
public class AppConfig {
    ...
}

&lt;beans&gt;
    &lt;context:component-scan base-package=&quot;org.example&quot;
        name-generator=&quot;org.example.MyNameGenerator&quot; /&gt;
&lt;/beans&gt;</code></pre><p>作为一般规则，考虑在其他组件可能对其进行显式引用时使用注解指定名称。 另一方面，只要容器负责装配时，自动生成的名称就足够了。</p>
<p><a id="beans-scanning-scope-resolver"></a></p>
<h4 id="1-10-7-为自动检测组件提供范围"><a href="#1-10-7-为自动检测组件提供范围" class="headerlink" title="1.10.7.为自动检测组件提供范围"></a><a href="#beans-scanning-scope-resolver"></a>1.10.7.为自动检测组件提供范围</h4><p>与一般的Spring管理组件一样，自动检测组件的默认和最常见的作用域是<code>singleton</code>。但是，有时您需要一个可由<code>@Scope</code>注解指定的不同作用域。 您可以在注解中提供作用域的名称，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Scope</span>(<span class="string">"prototype"</span>)</span><br><span class="line"><span class="meta">@Repository</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MovieFinderImpl</span> <span class="keyword">implements</span> <span class="title">MovieFinder</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>@Scope</code>注解仅在具体bean类（用于带注解的组件）或工厂方法（用于<code>@Bean</code>方法）上进行关联。 与XML bean定义相比，没有bean继承的概念，并且 类级别的继承结构与元数据无关。</p>
<p>有关特定于Web的范围（如Spring上下文中的“request” or “session”）的详细信息，请参阅<a href="#beans-factory-scopes-other">请求，会话，应用程序和WebSocket作用域</a>。 这些作用域与构建注解一样，您也可以使用Spring的元注解方法编写自己的作用域注解：例如，使用<code>@Scope(&quot;prototype&quot;)</code>进行元注解的自定义注解，可能还会声明自定义作用域代理模式。</p>
<p>想要提供自定义作用域的解析策略，而不是依赖于基于注解的方法，那么需要实现<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/annotation/ScopeMetadataResolver.html" target="_blank" rel="noopener"><code>ScopeMetadataResolver</code></a>接口，并确保包含一个默认的无参数构造函数。 然后，在配置扫描程序时提供完全限定类名。以下注解和bean定义示例显示：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ComponentScan</span>(basePackages = <span class="string">"org.example"</span>, scopeResolver = MyScopeResolver<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class"><span class="title">public</span> <span class="title">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&lt;beans&gt;</span><br><span class="line">    &lt;context:component-scan base-<span class="keyword">package</span>=<span class="string">"org.example"</span> scope-resolver=<span class="string">"org.example.MyScopeResolver"</span>/&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure>

<p>当使用某个非单例作用域时，为作用域对象生成代理可能非常必要，原因参看 <a href="#beans-factory-scopes-other-injection">作为依赖关系的作用域bean</a>。 为此，组件扫描元素上提供了scoped-proxy属性。 三个可能的值是：<code>no</code>, <code>interfaces</code>, 和 <code>targetClass</code>。 例如，以下配置导致标准JDK动态代理：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ComponentScan</span>(basePackages = <span class="string">"org.example"</span>, scopedProxy = ScopedProxyMode.INTERFACES)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&lt;beans&gt;</span><br><span class="line">    &lt;context:component-scan base-<span class="keyword">package</span>=<span class="string">"org.example"</span> scoped-proxy=<span class="string">"interfaces"</span>/&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure>

<p><a id="beans-scanning-qualifiers"></a></p>
<h4 id="1-10-8-为注解提供Qualifier元数据"><a href="#1-10-8-为注解提供Qualifier元数据" class="headerlink" title="1.10.8. 为注解提供Qualifier元数据"></a><a href="#beans-scanning-qualifiers"></a>1.10.8. 为注解提供Qualifier元数据</h4><p>在前面<a href="#beans-autowired-annotation-qualifiers">使用qualifiers微调基于注解自动装配</a>讨论过<code>@Qualifier</code> 注解。该部分中的示例演示了在解析自动注入候选者时使用 <code>@Qualifier</code>注解和自定义限定符注解以提供细粒度控制。 因为这些示例基于XML bean定义，所以使用XML中的<code>bean</code>元素的 <code>qualifier</code> 或 <code>meta</code>子元素在候选bean定义上提供了限定符元数据。当依靠类路径扫描并自动检测组件时， 可以在候选类上提供具有类型级别注解的限定符元数据。以下三个示例演示了此技术：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Qualifier</span>(<span class="string">"Action"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ActionMovieCatalog</span> <span class="keyword">implements</span> <span class="title">MovieCatalog</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Genre</span>(<span class="string">"Action"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ActionMovieCatalog</span> <span class="keyword">implements</span> <span class="title">MovieCatalog</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Offline</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CachingMovieCatalog</span> <span class="keyword">implements</span> <span class="title">MovieCatalog</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>与大多数基于注解的替代方法一样，注解元数据绑定到类定义本身，而使用在XML配置时，允许同一类型的beans在qualifier元数据中提供变量， 因为元数据是依据实例而不是类来提供的。</p>
<p><a id="beans-scanning-index"></a></p>
<h4 id="1-10-9-生成候选组件的索引"><a href="#1-10-9-生成候选组件的索引" class="headerlink" title="1.10.9. 生成候选组件的索引"></a><a href="#beans-scanning-index"></a>1.10.9. 生成候选组件的索引</h4><p>虽然类路径扫描非常快，但通过在编译时创建候选的静态列表。可以提高大型应用程序的启动性能。在此模式下，应用程序的所有模块都必须使用此机制， 当 <code>ApplicationContext</code>检测到此类索引时，它将自动使用它，而不是扫描类路径。</p>
<p>若要生成索引， 只需向包含组件扫描指令目标组件的每个模块添加一个附加依赖项。以下示例显示了如何使用Maven执行此操作：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependencies&gt;</span><br><span class="line">    &lt;dependency&gt;</span><br><span class="line">        &lt;groupId&gt;org.springframework&lt;/groupId&gt;</span><br><span class="line">        &lt;artifactId&gt;spring-context-indexer&lt;/artifactId&gt;</span><br><span class="line">        &lt;version&gt;5.1.3.BUILD-SNAPSHOT&lt;/version&gt;</span><br><span class="line">        &lt;optional&gt;true&lt;/optional&gt;</span><br><span class="line">    &lt;/dependency&gt;</span><br><span class="line">&lt;/dependencies&gt;</span><br></pre></td></tr></table></figure>

<p>以下示例显示了如何使用Gradle执行此操作:</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">dependencies &#123;</span><br><span class="line">    compileOnly(<span class="string">"org.springframework:spring-context-indexer:5.1.3.BUILD-SNAPSHOT"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个过程将产生一个名为<code>META-INF/spring.components</code>的文件，并将包含在jar包中。</p>
<p>在IDE中使用此模式时，必须将<code>spring-context-indexer</code>注册为注解处理器， 以确保更新候选组件时索引是最新的。</p>
<p>如果在类路径中找到 <code>META-INF/spring.components</code> 时，将自动启用索引。如果某个索引对于某些库(或用例)是不可用的， 但不能为整个应用程序构建，则可以将<code>spring.index.ignore</code>设置为<code>true</code>，从而将其回退到常规类路径的排列(即根本不存在索引)， 或者作为系统属性或在<code>spring.properties</code>文件位于类路径的根目录中。</p>
<p><a id="beans-standard-annotations"></a></p>
<h3 id="1-11-使用JSR-330标准注解"><a href="#1-11-使用JSR-330标准注解" class="headerlink" title="1.11. 使用JSR 330标准注解"></a><a href="#beans-standard-annotations"></a>1.11. 使用JSR 330标准注解</h3><p>从Spring 3.0开始，Spring提供对JSR-330标准注解（依赖注入）的支持。 这些注解的扫描方式与Spring注解相同。 要使用它们，您需要在类路径中包含相关的jar。</p>
<p>如果使用Maven工具，那么<code>@javax.inject.Inject</code>可以在Maven中央仓库中找到( <a href="https://repo1.maven.org/maven2/javax/inject/javax.inject/1/" target="_blank" rel="noopener">http://repo1.maven.org/maven2/javax/inject/javax.inject/1/</a>). 您可以将以下依赖项添加到文件pom.xml：:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.inject<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>javax.inject<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><a id="beans-inject-named"></a></p>
<h4 id="1-11-1-使用-Inject-和-Named注解实现依赖注入"><a href="#1-11-1-使用-Inject-和-Named注解实现依赖注入" class="headerlink" title="1.11.1. 使用@Inject 和 @Named注解实现依赖注入"></a><a href="#beans-inject-named"></a>1.11.1. 使用<code>@Inject</code> 和 <code>@Named</code>注解实现依赖注入</h4><p><code>@javax.inject.Inject</code>可以使用以下的方式来替代<code>@Autowired</code>注解:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> javax.inject.Inject;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Inject</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listMovies</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder.findMovies(...);</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>与 <code>@Autowired</code>一样，您可以在字段，方法和构造函数参数级别使用<code>@Inject</code>注解。此外，还可以将注入点声明为<code>Provider</code>。 它允许按需访问作用域较小的bean或通过<code>Provider.get()</code>调用对其他bean进行延迟访问。以下示例提供了前面示例的变体：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> javax.inject.Inject;</span><br><span class="line"><span class="keyword">import</span> javax.inject.Provider;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Provider&lt;MovieFinder&gt; movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Inject</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(Provider&lt;MovieFinder&gt; movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listMovies</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder.get().findMovies(...);</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果想要为注入的依赖项使用限定名称，则应该使用<code>@Named</code>注解。如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> javax.inject.Inject;</span><br><span class="line"><span class="keyword">import</span> javax.inject.Named;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Inject</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(@Named(<span class="string">"main"</span>)</span> MovieFinder movieFinder) </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>与<code>@Autowired</code>一样，<code>@Inject</code> 也可以与<code>java.util.Optional</code>或<code>@Nullable</code>一起使用。 这在这里用更适用，因为<code>@Inject</code>没有<code>required</code>的属性。 以下一对示例显示了如何使用<code>@Inject</code>和<code>@Nullable</code>:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Inject</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(Optional&lt;MovieFinder&gt; movieFinder)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Inject</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(@Nullable MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-named"></a></p>
<h4 id="1-11-2-Named-和-ManagedBean注解-标准与-Component-注解相同"><a href="#1-11-2-Named-和-ManagedBean注解-标准与-Component-注解相同" class="headerlink" title="1.11.2. @Named 和 @ManagedBean注解: 标准与 @Component 注解相同"></a><a href="#beans-named"></a>1.11.2. <code>@Named</code> 和 <code>@ManagedBean</code>注解: 标准与 <code>@Component</code> 注解相同</h4><p><code>@javax.inject.Named</code> 或 <code>javax.annotation.ManagedBean</code>可以使用下面的方式来替代<code>@Component</code>注解：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> javax.inject.Inject;</span><br><span class="line"><span class="keyword">import</span> javax.inject.Named;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Named</span>(<span class="string">"movieListener"</span>)  <span class="comment">// @ManagedBean("movieListener") could be used as well</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Inject</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在不指定组件名称的情况下使用<code>@Component</code>是很常见的。 <code>@Named</code>可以以类似的方式使用，如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> javax.inject.Inject;</span><br><span class="line"><span class="keyword">import</span> javax.inject.Named;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Named</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMovieLister</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MovieFinder movieFinder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Inject</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMovieFinder</span><span class="params">(MovieFinder movieFinder)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.movieFinder = movieFinder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当使用<code>@Named</code> 或 <code>@ManagedBean</code>时，可以与Spring注解完全相同的方式使用component-scanning组件扫描。 如以下示例所示:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ComponentScan</span>(basePackages = <span class="string">"org.example"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span>  </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>与<code>@Component</code>相反，JSR-330 <code>@Named</code> 和 JSR-250 <code>ManagedBean</code>注解不可组合。 请使用Spring的原型模型（stereotype mode)来构建自定义组件注解。</p>
<p><a id="beans-standard-annotations-limitations"></a></p>
<h4 id="1-11-3-使用-JSR-330标准注解的限制"><a href="#1-11-3-使用-JSR-330标准注解的限制" class="headerlink" title="1.11.3. 使用 JSR-330标准注解的限制"></a><a href="#beans-standard-annotations-limitations"></a>1.11.3. 使用 JSR-330标准注解的限制</h4><p>使用标准注解时，需要知道哪些重要功能是不可用的。如下表所示：</p>
<p>Table 6. Spring的组件模型元素 vs JSR-330 变量</p>
<table>
<thead>
<tr>
<th>Spring</th>
<th>javax.inject.*</th>
<th>javax.inject restrictions / comments</th>
</tr>
</thead>
<tbody><tr>
<td>@Autowired</td>
<td>@Inject</td>
<td><code>@Inject</code> 没有’required’属性。 可以与Java 8的 <code>Optional</code>一起使用。</td>
</tr>
<tr>
<td>@Component</td>
<td>@Named / @ManagedBean</td>
<td>JSR-330不提供可组合模型，只是一种识别命名组件的方法。</td>
</tr>
<tr>
<td>@Scope(“singleton”)</td>
<td>@Singleton</td>
<td>JSR-330的默认作用域就像Spring的<code>prototype</code>。 但是，为了使其与Spring的一般默认值保持一致，默认情况下，Spring容器中声明的JSR-330 bean是一个 <code>singleton</code>。 为了使用除 <code>singleton</code>之外的范围，您应该使用Spring的<code>@Scope</code>注解。 <code>javax.inject</code>还提供了<a href="https://download.oracle.com/javaee/6/api/javax/inject/Scope.html" target="_blank" rel="noopener">@Scope</a>注解。 然而，这个仅用于创建自己的注解。</td>
</tr>
<tr>
<td>@Qualifier</td>
<td>@Qualifier / @Named</td>
<td><code>javax.inject.Qualifier</code> 只是用于构建自定义限定符的元注解。 可以通过<code>javax.inject.Named</code>创建与Spring中<code>@Qualifier</code>一样的限定符。</td>
</tr>
<tr>
<td>@Value</td>
<td>-</td>
<td>无</td>
</tr>
<tr>
<td>@Required</td>
<td>-</td>
<td>无</td>
</tr>
<tr>
<td>@Lazy</td>
<td>-</td>
<td>无</td>
</tr>
<tr>
<td>ObjectFactory</td>
<td>Provider</td>
<td><code>javax.inject.Provider</code> avax.inject.Provider是Spring的<code>ObjectFactory</code>的直接替代品， 仅仅使用简短的<code>get()</code>方法即可。 它也可以与Spring的<code>@Autowired</code>结合使用，也可以与非注解的构造函数和setter方法结合使用。</td>
</tr>
</tbody></table>
<p><a id="beans-java"></a></p>
<h3 id="1-12-基于Java的容器配置"><a href="#1-12-基于Java的容器配置" class="headerlink" title="1.12. 基于Java的容器配置"></a><a href="#beans-java"></a>1.12. 基于Java的容器配置</h3><p>本节介绍如何在Java代码中使用注解来配置Spring容器。 它包括以下主题：:</p>
<ul>
<li><p><a href="#beans-java-basic-concepts">基本概念: <code>@Bean</code> 和 <code>@Configuration</code></a></p>
</li>
<li><p><a href="#beans-java-instantiating-container">使用<code>AnnotationConfigApplicationContext</code>实例化Spring容器</a></p>
</li>
<li><p><a href="#beans-java-bean-annotation">使用<code>@Bean</code>注解</a></p>
</li>
<li><p><a href="#beans-java-configuration-annotation">使用<code>@Configuration</code>注解</a></p>
</li>
<li><p><a href="#beans-java-composing-configuration-classes">编写基于Java的配置</a></p>
</li>
<li><p><a href="#beans-definition-profiles">定义Bean配置文件</a></p>
</li>
<li><p><a href="#beans-property-source-abstraction"><code>PropertySource</code> 抽象</a></p>
</li>
<li><p><a href="#beans-using-propertysource">使用 <code>@PropertySource</code></a></p>
</li>
<li><p><a href="#beans-placeholder-resolution-in-statements">声明中的占位符</a></p>
</li>
</ul>
<p><a id="beans-java-basic-concepts"></a></p>
<h4 id="1-12-1-基本概念-Bean-和-Configuration"><a href="#1-12-1-基本概念-Bean-和-Configuration" class="headerlink" title="1.12.1. 基本概念: @Bean 和 @Configuration"></a><a href="#beans-java-basic-concepts"></a>1.12.1. 基本概念: <code>@Bean</code> 和 <code>@Configuration</code></h4><p>Spring新的基于Java配置的核心内容是<code>@Configuration</code>注解的类和<code>@Bean</code>注解的方法。</p>
<p><code>@Bean</code>注解用于表明方法的实例化，、配置和初始化都是由Spring IoC容器管理的新对象，对于那些熟悉Spring的<code>&lt;beans/&gt;</code>XML配置的人来说， <code>@Bean</code>注解扮演的角色与<code>&lt;beans/&gt;</code>元素相同。开发者可以在任意的Spring <code>@Component</code>中使用<code>@Bean</code>注解方法 ，但大多数情况下，<code>@Bean</code>是配合<code>@Configuration</code>使用的。</p>
<p>使用<code>@Configuration</code>注解类时，这个类的目的就是作为bean定义的地方。此外，<code>@Configuration</code>类允许通过调用同一个类中的其他<code>@Bean</code>方法来定义bean间依赖关系。 最简单的<code>@Configuration</code>类如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> MyService <span class="title">myService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MyServiceImpl();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>前面的<code>AppConfig</code>类等效于以下Spring <code>&lt;beans/&gt;</code>XML：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"myService"</span> <span class="attr">class</span>=<span class="string">"com.acme.services.MyServiceImpl"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>完整的@Configuration模式对比“lite”模式的@Bean?</p>
<p>当<code>@Bean</code>方法在没有用 <code>@Configuration</code>注解的类中声明时，它们将会被称为“lite”的模式处理。例如，<code>@Component</code>中声明的bean方法或者一个普通的旧类中的bean方法将被视为 “lite”的。包含类的主要目的不同，而<code>@Bean</code>方法在这里是一种额外的好处。。例如，服务组件可以通过在每个适用的组件类上使用额外的 <code>@Bean</code>方法将管理视图公开给容器。 在这种情况下，<code>@Bean</code>方法是一种通用的工厂方法机制。</p>
<p>与完整的 <code>@Configuration</code>不同，lite的<code>@Bean</code>方法不能声明bean之间的依赖关系。 相反，它们对其包含组件的内部状态进行操作，并且可以有选择的对它们可能声明的参数进行操作。因此，这样的<code>@Bean</code>注解的方法不应该调用其他<code>@Bean</code>注解的方法。 每个这样的方法实际上只是特定bean引用的工厂方法，没有任何特殊的运行时语义。不经过CGLIB处理，所以在类设计方面没有限制（即，包含类可能是最终的）。</p>
<p>在常见的场景中，<code>@Bean</code>方法将在<code>@Configuration</code>类中声明，确保始终使用“full”模式，这将防止相同的<code>@Bean</code>方法被意外地多次调用，这有助于减少在 “lite”模式下操作时难以跟踪的细微错误。</p>
<p><code>@Bean</code>和<code>@Configuration</code>注解将在下面的章节深入讨论，首先，我们将介绍使用基于Java代码的配置来创建Spring容器的各种方法。</p>
<p><a id="beans-java-instantiating-container"></a></p>
<h4 id="1-12-2-使用AnnotationConfigApplicationContext初始化Spring容器"><a href="#1-12-2-使用AnnotationConfigApplicationContext初始化Spring容器" class="headerlink" title="1.12.2. 使用AnnotationConfigApplicationContext初始化Spring容器"></a><a href="#beans-java-instantiating-container"></a>1.12.2. 使用<code>AnnotationConfigApplicationContext</code>初始化Spring容器</h4><p>以下部分介绍了Spring的<code>AnnotationConfigApplicationContext</code>，它是在Spring 3.0中引入的。这是一个强大的(versatile)<code>ApplicationContext</code> 实现,它不仅能解析<code>@Configuration</code>注解类 ,也能解析 <code>@Component</code>注解的类和使用JSR-330注解的类.</p>
<p>当使用<code>@Configuration</code>类作为输入时,<code>@Configuration</code>类本身被注册为一个bean定义,类中所有声明的<code>@Bean</code>方法也被注册为bean定义.</p>
<p>当提供 <code>@Component</code>和JSR-330类时，它们被注册为bean定义，并且假定在必要时在这些类中使用DI元数据，例如<code>@Autowired</code> 或 <code>@Inject</code>。</p>
<p><a id="beans-java-instantiating-container-contstructor"></a></p>
<h5 id="简单结构"><a href="#简单结构" class="headerlink" title="简单结构"></a><a href="#beans-java-instantiating-container-contstructor"></a>简单结构</h5><p>与实例化<code>ClassPathXmlApplicationContext</code>时Spring XML文件用作输入的方式大致相同， 在实例化<code>AnnotationConfigApplicationContext</code>时可以使用<code>@Configuration</code> 类作为输入。 这允许完全无XML使用Spring容器，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ApplicationContext ctx = <span class="keyword">new</span> AnnotationConfigApplicationContext(AppConfig<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    MyService myService = ctx.getBean(MyService<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    myService.doStuff();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如前所述，<code>AnnotationConfigApplicationContext</code>不仅限于使用<code>@Configuration</code>类。 任何<code>@Component</code>或JSR-330带注解的类都可以作为输入提供给构造函数，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ApplicationContext ctx = <span class="keyword">new</span> AnnotationConfigApplicationContext(MyServiceImpl<span class="class">.<span class="keyword">class</span>, <span class="title">Dependency1</span>.<span class="title">class</span>, <span class="title">Dependency2</span>.<span class="title">class</span>)</span>;</span><br><span class="line">    MyService myService = ctx.getBean(MyService<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    myService.doStuff();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面假设<code>MyServiceImpl</code>, <code>Dependency1</code>, 和 <code>Dependency2</code>使用Spring依赖注入注解，例如<code>@Autowired</code>。</p>
<p><a id="beans-java-instantiating-container-register"></a></p>
<h5 id="使用register-Class-lt-gt-…-编程构建容器"><a href="#使用register-Class-lt-gt-…-编程构建容器" class="headerlink" title="使用register(Class&lt;?&gt;…)编程构建容器"></a><a href="#beans-java-instantiating-container-register"></a>使用<code>register(Class&lt;?&gt;…)</code>编程构建容器</h5><p><code>AnnotationConfigApplicationContext</code>可以通过无参构造函数实例化，然后调用<code>register()</code> 方法进行配置。 这种方法在以编程的方式构建 <code>AnnotationConfigApplicationContext</code>时特别有用。下列示例显示了如何执行此操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    AnnotationConfigApplicationContext ctx = <span class="keyword">new</span> AnnotationConfigApplicationContext();</span><br><span class="line">    ctx.register(AppConfig<span class="class">.<span class="keyword">class</span>, <span class="title">OtherConfig</span>.<span class="title">class</span>)</span>;</span><br><span class="line">    ctx.register(AdditionalConfig<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    ctx.refresh();</span><br><span class="line">    MyService myService = ctx.getBean(MyService<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    myService.doStuff();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-java-instantiating-container-scan"></a></p>
<h5 id="3-使用scan-String…-扫描组件"><a href="#3-使用scan-String…-扫描组件" class="headerlink" title="3 使用scan(String…)扫描组件"></a><a href="#beans-java-instantiating-container-scan"></a>3 使用<code>scan(String…)</code>扫描组件</h5><p>要启用组件扫描，可以按如下方式注解<code>@Configuration</code>类:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ComponentScan</span>(basePackages = <span class="string">"com.acme"</span>) (<span class="number">1</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span>  </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1</strong>、此注解可启用组件扫描。</p>
<p>有经验的用户可能更熟悉使用XML的等价配置形式，如下例所示：</p>
<pre><code>&lt;beans&gt;
    &lt;context:component-scan base-package=&quot;com.acme&quot;/&gt;
&lt;/beans&gt;</code></pre><p>上面的例子中，<code>com.acme</code>包会被扫描，只要是使用了<code>@Component</code>注解的类，都会被注册进容器中。同样地，<code>AnnotationConfigApplicationContext</code>公开的<code>scan(String…)</code> 方法也允许扫描类完成同样的功能 如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    AnnotationConfigApplicationContext ctx = <span class="keyword">new</span> AnnotationConfigApplicationContext();</span><br><span class="line">    ctx.scan(<span class="string">"com.acme"</span>);</span><br><span class="line">    ctx.refresh();</span><br><span class="line">    MyService myService = ctx.getBean(MyService<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>请记住<code>@Configuration</code>类是使用<code>@Component</code>进行<a href="#beans-meta-annotations">元注解</a>的，因此它们是组件扫描的候选者。 在前面的示例中， 假设AppConfig在com.acme包（或下面的任何包）中声明，它在<code>scan()</code>调用期间被拾取。 在<code>refresh()</code>之后，它的所有<code>@Bean</code>方法都被处理并在容器中注册为bean定义。</p>
<p><a id="beans-java-instantiating-container-web"></a></p>
<h5 id="使用AnnotationConfigWebApplicationContext支持Web应用程序"><a href="#使用AnnotationConfigWebApplicationContext支持Web应用程序" class="headerlink" title="使用AnnotationConfigWebApplicationContext支持Web应用程序"></a><a href="#beans-java-instantiating-container-web"></a>使用<code>AnnotationConfigWebApplicationContext</code>支持Web应用程序</h5><p><code>WebApplicationContext</code>与<code>AnnotationConfigApplicationContext</code>的变种是 <code>AnnotationConfigWebApplicationContext</code>配置。这个实现可以用于配置Spring <code>ContextLoaderListener</code> servlet监听器 ，Spring MVC的 <code>DispatcherServlet</code>等等。以下web.xml代码段配置典型的Spring MVC Web应用程序（请注意<code>contextClass</code> context-param和init-param的使用）：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">web-app</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext</span></span><br><span class="line"><span class="comment">        instead of the default XmlWebApplicationContext --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context-param</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextClass<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-value</span>&gt;</span></span><br><span class="line">            org.springframework.web.context.support.AnnotationConfigWebApplicationContext</span><br><span class="line">        <span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">context-param</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- Configuration locations must consist of one or more comma- or space-delimited</span></span><br><span class="line"><span class="comment">        fully-qualified @Configuration classes. Fully-qualified packages may also be</span></span><br><span class="line"><span class="comment">        specified for component-scanning --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context-param</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>com.acme.AppConfig<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">context-param</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- Bootstrap the root application context as usual using ContextLoaderListener --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">listener</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">listener-class</span>&gt;</span>org.springframework.web.context.ContextLoaderListener<span class="tag">&lt;/<span class="name">listener-class</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">listener</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- Declare a Spring MVC DispatcherServlet as usual --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>dispatcher<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>org.springframework.web.servlet.DispatcherServlet<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext</span></span><br><span class="line"><span class="comment">            instead of the default XmlWebApplicationContext --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextClass<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-value</span>&gt;</span></span><br><span class="line">                org.springframework.web.context.support.AnnotationConfigWebApplicationContext</span><br><span class="line">            <span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- Again, config locations must consist of one or more comma- or space-delimited</span></span><br><span class="line"><span class="comment">            and fully-qualified @Configuration classes --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>com.acme.web.MvcConfig<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- map all requests for /app/* to the dispatcher servlet --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>dispatcher<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/app/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><a id="beans-java-bean-annotation"></a></p>
<h4 id="1-12-3-使用-Bean-注解"><a href="#1-12-3-使用-Bean-注解" class="headerlink" title="1.12.3. 使用@Bean 注解"></a><a href="#beans-java-bean-annotation"></a>1.12.3. 使用<code>@Bean</code> 注解</h4><p><code>@Bean</code> @Bean是一个方法级别的注解，它与XML中的 <code>&lt;bean/&gt;</code>元素类似。注解支持 <code>&lt;bean/&gt;</code>提供的一些属性，例如 * <a href="#beans-factory-lifecycle-initializingbean">init-method</a> * <a href="#beans-factory-lifecycle-disposablebean">destroy-method</a> * <a href="#beans-factory-autowire">autowiring</a> * <code>name</code></p>
<p>开发者可以在<code>@Configuration</code>类或<code>@Component</code>类中使用<code>@Bean</code>注解。</p>
<p><a id="beans-java-declaring-a-bean"></a></p>
<h5 id="声明一个Bean"><a href="#声明一个Bean" class="headerlink" title="声明一个Bean"></a><a href="#beans-java-declaring-a-bean"></a>声明一个Bean</h5><p>要声明一个bean，只需使用<code>@Bean</code>注解方法即可。使用此方法，将会在<code>ApplicationContext</code>内注册一个bean，bean的类型是方法的返回值类型。默认情况下， bean名称将与方法名称相同。以下示例显示了<code>@Bean</code>方法声明：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransferServiceImpl <span class="title">transferService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TransferServiceImpl();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>前面的配置完全等同于以下Spring XML:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"transferService"</span> <span class="attr">class</span>=<span class="string">"com.acme.TransferServiceImpl"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>这两个声明都在<code>ApplicationContext</code>中创建一个名为<code>transferService</code>的bean，并且绑定了<code>TransferServiceImpl</code>的实例。如下图所示：</p>
<p>transferService -&gt; com.acme.TransferServiceImpl</p>
<p>您还可以使用接口（或基类）返回类型声明<code>@Bean</code>方法，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransferService <span class="title">transferService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TransferServiceImpl();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但是，这会将预先类型预测的可见性限制为指定的接口类型(<code>TransferService</code>),然后在实例化受影响的单一bean时,只知道容器的完整类型(<code>TransferServiceImpl</code>）。 。非延迟的单例bean根据它们的声明顺序进行实例化，因此开发者可能会看到不同类型的匹配结果，这具体取决于另一个组件尝试按未类型匹配的时间(如<code>@Autowired TransferServiceImpl</code>， 一旦<code>transferService</code> bean已被实例化,这个问题就被解决了).</p>
<p>如果通过声明的服务接口都是引用类型,那么<code>@Bean</code> 返回类型可以安全地加入该设计决策.但是,对于实现多个接口的组件或可能由其实现类型引用的组件, 更安全的方法是声明可能的最具体的返回类型(至少按照注入点所要求的特定你的bean）。</p>
<p><a id="beans-java-dependencies"></a></p>
<h5 id="Bean之间的依赖"><a href="#Bean之间的依赖" class="headerlink" title="Bean之间的依赖"></a><a href="#beans-java-dependencies"></a>Bean之间的依赖</h5><p>一个使用<code>@Bean</code>注解的方法可以具有任意数量的参数描述构建该bean所需的依赖，例如，如果我们的<code>TransferService</code>需要<code>AccountRepository</code>， 我们可以使用方法参数来实现该依赖关系，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransferService <span class="title">transferService</span><span class="params">(AccountRepository accountRepository)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TransferServiceImpl(accountRepository);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个解析机制与基于构造函数的依赖注入非常相似。有关详细信息，请参阅<a href="#beans-constructor-injection">相关部分</a>。</p>
<p><a id="beans-java-lifecycle-callbacks"></a></p>
<h5 id="接收生命周期回调"><a href="#接收生命周期回调" class="headerlink" title="接收生命周期回调"></a><a href="#beans-java-lifecycle-callbacks"></a>接收生命周期回调</h5><p>使用<code>@Bean</code>注解定义的任何类都支持常规的生命周期回调，并且可以使用JSR-的<code>@PostConstruct</code>和<code>@PreDestroy</code>注解。 有关更多详细信息，请参阅 <a href="#beans-postconstruct-and-predestroy-annotations">JSR-250</a> 注解。</p>
<p>完全支持常规的Spring<a href="#beans-factory-nature">生命周期</a>回调。 如果bean实现<code>InitializingBean</code>, <code>DisposableBean</code>, 或 <code>Lifecycle</code>，则它们各自的方法由容器调用。</p>
<p>同样地，还完全支持标准的<code>*Aware</code>，如<a href="#beans-beanfactory">BeanFactoryAware</a>, <a href="#beans-factory-aware">BeanNameAware</a>, <a href="#context-functionality-messagesource">MessageSourceAware</a>, <a href="#beans-factory-aware">ApplicationContextAware</a>。</p>
<p><code>@Bean</code>注解支持指定任意初始化和销毁回调方法，就像<code>bean</code>元素上的Spring XML的 <code>init-method</code>和<code>destroy-method</code> 属性一样，如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BeanOne</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// initialization logic</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BeanTwo</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">cleanup</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// destruction logic</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(initMethod = <span class="string">"init"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> BeanOne <span class="title">beanOne</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> BeanOne();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(destroyMethod = <span class="string">"cleanup"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> BeanTwo <span class="title">beanTwo</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> BeanTwo();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>默认情况下，使用Java Config定义的bean中<code>close</code>方法或者<code>shutdown</code>方法，会作为销毁回调而自动调用。若bean中有<code>close</code> 或 <code>shutdown</code> 方法，并且您不希望在容器关闭时调用它，则可以将<code>@Bean(destroyMethod=&quot;&quot;)</code> 添加到bean定义中以禁用默认<code>(inferred)</code> 模式。</p>
<p>开发者可能希望对通过JNDI获取的资源执行此操作，因为它的生命周期是在应用程序外部管理的。更进一步，使用 <code>DataSource</code>时一定要关闭它，不关闭将会出问题。</p>
<p>以下示例说明如何防止<code>DataSource</code>的自动销毁回调：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span>(destroyMethod=<span class="string">""</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> <span class="keyword">throws</span> NamingException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (DataSource) jndiTemplate.lookup(<span class="string">"MyDS"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>同样地，使用<code>@Bean</code>方法，通常会选择使用程序化的JNDI查找：使用Spring的<code>JndiTemplate</code> / <code>JndiLocatorDelegate</code>帮助类或直接使用JNDI的<code>InitialContext</code> ，但是不要使用<code>JndiObjectFactoryBean</code>的变体，因为它会强制开发者声明一个返回类型作为<code>FactoryBean</code>的类型用于代替实际的目标类型，这会使得交叉引用变得很困难。</p>
<p>对于前面注解中上面示例中的<code>BeanOne</code>，在构造期间直接调用<code>init()</code>方法同样有效，如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> BeanOne <span class="title">beanOne</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        BeanOne beanOne = <span class="keyword">new</span> BeanOne();</span><br><span class="line">        beanOne.init();</span><br><span class="line">        <span class="keyword">return</span> beanOne;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当您直接使用Java（new对象那种）工作时，您可以使用对象执行任何您喜欢的操作，并且不必总是依赖于容器生命周期。</p>
<p><a id="beans-java-specifying-bean-scope"></a></p>
<h5 id="指定Bean范围"><a href="#指定Bean范围" class="headerlink" title="指定Bean范围"></a><a href="#beans-java-specifying-bean-scope"></a>指定Bean范围</h5><p>Spring包含<code>@Scope</code>注解，以便您可以指定bean的范围。</p>
<p><a id="beans-java-available-scopes"></a></p>
<h6 id="使用-Scope-注解"><a href="#使用-Scope-注解" class="headerlink" title="使用 @Scope 注解"></a><a href="#beans-java-available-scopes"></a>使用 <code>@Scope</code> 注解</h6><p>可以使用任意标准的方式为 <code>@Bean</code>注解的bean指定一个作用域，你可以使用<a href="#beans-factory-scopes">Bean Scopes</a>中的任意标准作用域</p>
<p>默认范围是<code>singleton</code>的，但是可以使用 <code>@Scope</code>注解来覆盖。如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@Scope</span>(<span class="string">"prototype"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Encryptor <span class="title">encryptor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-java-scoped-proxy"></a></p>
<h6 id="Scope-and-scoped-proxy"><a href="#Scope-and-scoped-proxy" class="headerlink" title="@Scope and scoped-proxy"></a><a href="#beans-java-scoped-proxy"></a><code>@Scope</code> and <code>scoped-proxy</code></h6><p>Spring提供了一种通过<a href="#beans-factory-scopes-other-injection">scoped proxies</a>处理作用域依赖项的便捷方法。使用XML配置时创建此类代理的最简单方法是<code>&lt;aop:scoped-proxy/&gt;</code>元素。 使用<code>@Scope</code>注解在Java中配置bean提供了与<code>proxyMode</code>属性的等效支持。 默认值为无代理（<code>ScopedProxyMode.NO</code>），但您可以指定<code>ScopedProxyMode.TARGET_CLASS</code> 或 <code>ScopedProxyMode.INTERFACES</code>。</p>
<p>如果使用Java将XML参考文档（请参阅<a href="#beans-factory-scopes-other-injection">scoped proxies</a>）的作用域代理示例移植到我们的 <code>@Bean</code>，它类似于以下内容：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// an HTTP Session-scoped bean exposed as a proxy</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="meta">@SessionScope</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> UserPreferences <span class="title">userPreferences</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> UserPreferences();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Service <span class="title">userService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    UserService service = <span class="keyword">new</span> SimpleUserService();</span><br><span class="line">    <span class="comment">// a reference to the proxied userPreferences bean</span></span><br><span class="line">    service.setUserPreferences(userPreferences());</span><br><span class="line">    <span class="keyword">return</span> service;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-java-customizing-bean-naming"></a></p>
<h5 id="自定义Bean命名"><a href="#自定义Bean命名" class="headerlink" title="自定义Bean命名"></a><a href="#beans-java-customizing-bean-naming"></a>自定义Bean命名</h5><p>默认情况下，配置类使用<code>@Bean</code>方法的名称作为结果bean的名称。 但是，可以使用<code>name</code>属性覆盖此功能，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"myThing"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Thing <span class="title">thing</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Thing();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-java-bean-aliasing"></a></p>
<h5 id="bean别名"><a href="#bean别名" class="headerlink" title="bean别名"></a><a href="#beans-java-bean-aliasing"></a>bean别名</h5><p>正如<a href="#beans-beanname">Bean的 命名</a>中所讨论的，有时需要为单个bean提供多个名称，也称为bean别名。 <code>@Bean</code>注解的 <code>name</code>属性为此接受String数组。 以下示例显示如何为bean设置多个别名：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(name = &#123; <span class="string">"dataSource"</span>, <span class="string">"subsystemA-dataSource"</span>, <span class="string">"subsystemB-dataSource"</span> &#125;)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// instantiate, configure and return DataSource bean...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-java-bean-description"></a></p>
<h5 id="Bean-的描述"><a href="#Bean-的描述" class="headerlink" title="Bean 的描述"></a><a href="#beans-java-bean-description"></a>Bean 的描述</h5><p>有时，提供更详细的bean文本描述会很有帮助。 当bean被暴露（可能通过JMX）用于监视目的时，这可能特别有用。</p>
<p>要向@Bean添加描述，可以使用<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/annotation/Description.html" target="_blank" rel="noopener"><code>@Description</code></a>注解，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@Description</span>(<span class="string">"Provides a basic example of a bean"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Thing <span class="title">thing</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Thing();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-java-configuration-annotation"></a></p>
<h4 id="1-12-4-使用-Configuration-注解"><a href="#1-12-4-使用-Configuration-注解" class="headerlink" title="1.12.4. 使用 @Configuration 注解"></a><a href="#beans-java-configuration-annotation"></a>1.12.4. 使用 <code>@Configuration</code> 注解</h4><p><code>@Configuration</code>是一个类级别的注解,表明该类将作为bean定义的元数据配置. <code>@Configuration</code>类会将有<code>@Bean</code>注解的公开方法声明为bean, .在 <code>@Configuration</code>类上调用<code>@Bean</code>方法也可以用于定义bean间依赖关系, 有关一般介绍，请参阅 <a href="#beans-java-basic-concepts">基本概念: <code>@Bean</code> 和 <code>@Configuration</code></a></p>
<p><a id="beans-java-injecting-dependencies"></a></p>
<h5 id="注入内部bean依赖"><a href="#注入内部bean依赖" class="headerlink" title="注入内部bean依赖"></a><a href="#beans-java-injecting-dependencies"></a>注入内部bean依赖</h5><p>当Bean彼此有依赖关系时,表示依赖关系就像调用另一个bean方法一样简单.如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> BeanOne <span class="title">beanOne</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> BeanOne(beanTwo());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> BeanTwo <span class="title">beanTwo</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> BeanTwo();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在前面的示例中，<code>beanOne</code>通过构造函数注入接收对<code>beanTwo</code>的引用。</p>
<p>这种声明bean间依赖关系的方法只有在 <code>@Configuration</code> 类中声明<code>@Bean</code>方法时才有效。 您不能使用普通的<code>@Component</code>类声明bean间依赖关系。</p>
<p><a id="beans-java-method-injection"></a></p>
<h5 id="查找方法注入-1"><a href="#查找方法注入-1" class="headerlink" title="查找方法注入"></a><a href="#beans-java-method-injection"></a>查找方法注入</h5><p>如前所述，<a href="#beans-factory-method-injection">查找方法注入</a>是一项很少使用的高级功能。 在单例范围的bean依赖于原型范围的bean的情况下，它很有用。 Java提供了很友好的API来实现这种模式。以下示例显示了如何使用查找方法注入：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">CommandManager</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">process</span><span class="params">(Object commandState)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// grab a new instance of the appropriate Command interface</span></span><br><span class="line">        Command command = createCommand();</span><br><span class="line">        <span class="comment">// set the state on the (hopefully brand new) Command instance</span></span><br><span class="line">        command.setState(commandState);</span><br><span class="line">        <span class="keyword">return</span> command.execute();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// okay... but where is the implementation of this method?</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> Command <span class="title">createCommand</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>通过使用Java配置，您可以创建 <code>CommandManager</code>的子类，其中抽象的 <code>createCommand()</code> 方法被覆盖，以便查找新的（原型）对象。 以下示例显示了如何执行此操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="meta">@Scope</span>(<span class="string">"prototype"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> AsyncCommand <span class="title">asyncCommand</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    AsyncCommand command = <span class="keyword">new</span> AsyncCommand();</span><br><span class="line">    <span class="comment">// inject dependencies here as required</span></span><br><span class="line">    <span class="keyword">return</span> command;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> CommandManager <span class="title">commandManager</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// return new anonymous implementation of CommandManager with command() overridden</span></span><br><span class="line">    <span class="comment">// to return a new prototype Command object</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> CommandManager() &#123;</span><br><span class="line">        <span class="function"><span class="keyword">protected</span> Command <span class="title">createCommand</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> asyncCommand();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="beans-java-further-information-java-config"></a></p>
<h5 id="有关基于Java的配置如何在内部工作的更多信息"><a href="#有关基于Java的配置如何在内部工作的更多信息" class="headerlink" title="有关基于Java的配置如何在内部工作的更多信息"></a><a href="#beans-java-further-information-java-config"></a>有关基于Java的配置如何在内部工作的更多信息</h5><p>请考虑以下示例，该示例显示了被调用两次的<code>@Bean</code>注解方法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ClientService <span class="title">clientService1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ClientServiceImpl clientService = <span class="keyword">new</span> ClientServiceImpl();</span><br><span class="line">        clientService.setClientDao(clientDao());</span><br><span class="line">        <span class="keyword">return</span> clientService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ClientService <span class="title">clientService2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ClientServiceImpl clientService = <span class="keyword">new</span> ClientServiceImpl();</span><br><span class="line">        clientService.setClientDao(clientDao());</span><br><span class="line">        <span class="keyword">return</span> clientService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ClientDao <span class="title">clientDao</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ClientDaoImpl();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>clientDao()</code>在<code>clientService1()</code>中调用一次，在<code>clientService2()</code>中调用一次。由于此方法创建了<code>ClientDaoImpl</code>的新实例并将其返回，因此通常希望有两个实例（每个服务一个）。 这肯定会有问题：在Spring中，实例化的bean默认具有<code>singleton</code>范围。这就是它的神奇之处:所有<code>@Configuration</code>类在启动时都使用 <code>CGLIB</code>进行子类化。 在子类中，子方法在调用父方法并创建新实例之前，首先检查容器是否有任何缓存（作用域）bean。</p>
<p>这种行为可以根据bean的作用域而变化,我们这里只是讨论单例.</p>
<p>从Spring 3.2开始，不再需要将CGLIB添加到类路径中，因为CGLIB类已经在<code>org.springframework.cglib</code>下重新打包并直接包含在spring-core JAR中。</p>
<p>由于CGLIB在启动时动态添加功能，因此存在一些限制。 特别是，配置类不能是 final的。 但是，从4.3开始，配置类允许使用任何构造函数，包括使用<code>@Autowired</code>或单个非默认构造函数声明进行默认注入。</p>
<p>如果想避免因CGLIB带来的限制,请考虑声明非<code>@Configuration</code>类的<code>@Bean</code>方法，例如在纯的<code>@Component</code>类 .这样在<code>@Bean</code>方法之间的交叉方法调用将不会被拦截,此时必须在构造函数或方法级别上进行依赖注入。</p>
<p><a id="beans-java-composing-configuration-classes"></a></p>
<h4 id="1-12-5-编写基于Java的配置"><a href="#1-12-5-编写基于Java的配置" class="headerlink" title="1.12.5. 编写基于Java的配置"></a><a href="#beans-java-composing-configuration-classes"></a>1.12.5. 编写基于Java的配置</h4><p>Spring的基于Java的配置功能允许您撰写注解，这可以降低配置的复杂性。</p>
<p><a id="beans-java-using-import"></a></p>
<h5 id="使用-Import-注解"><a href="#使用-Import-注解" class="headerlink" title="使用@Import 注解"></a><a href="#beans-java-using-import"></a>使用<code>@Import</code> 注解</h5><p>就像在Spring XML文件中使用<code>&lt;import/&gt;</code>元素来帮助模块化配置一样，<code>@Import</code> 注解允许从另一个配置类加载<code>@Bean</code>定义，如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ConfigA</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> A <span class="title">a</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> A();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Import</span>(ConfigA<span class="class">.<span class="keyword">class</span>)</span></span><br><span class="line"><span class="class"><span class="title">public</span> <span class="title">class</span> <span class="title">ConfigB</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> B <span class="title">b</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> B();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在，在实例化上下文时，不需要同时指定<code>ConfigA.class</code>和 <code>ConfigB.class</code>，只需要显式提供<code>ConfigB</code>，如下例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ApplicationContext ctx = <span class="keyword">new</span> AnnotationConfigApplicationContext(ConfigB<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// now both beans A and B will be available...</span></span><br><span class="line">    A a = ctx.getBean(A<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    B b = ctx.getBean(B<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这种方法简化了容器实例化，因为只需要处理一个类，而不是要求您在构造期间记住可能大量的<code>@Configuration</code>类。</p>
<p>从Spring Framework 4.2开始，<code>@Import</code>还支持引用常规组件类，类似于<code>AnnotationConfigApplicationContext.register</code>方法。 如果要避免组件扫描，这一点特别有用，可以使用一些配置类作为明确定义所有组件的入口点。</p>
<p><a id="beans-java-injecting-imported-beans"></a></p>
<h6 id="在导入的-Bean定义上注入依赖项"><a href="#在导入的-Bean定义上注入依赖项" class="headerlink" title="在导入的@Bean定义上注入依赖项"></a><a href="#beans-java-injecting-imported-beans"></a>在导入的<code>@Bean</code>定义上注入依赖项</h6><p>上面的例子可以运行,,但是太简单了。在大多数实际情况下，bean将在配置类之间相互依赖.在使用XML时,这本身不是问题,因为没有涉及到编译器. 可以简单地声明 <code>ref=&quot;someBean&quot;</code>,并且相信Spring将在容器初始化期间可以很好地处理它。当然，当使用<code>@Configuration</code>类时，Java编译器会有一些限制 ，即需符合Java的语法。</p>
<p>幸运的是，解决这个问题很简单。正如我们<a href="#beans-java-dependencies">已经讨论过</a>的，<code>@Bean</code>方法可以有任意数量的参数来描述bean的依赖关系。 考虑以下更多真实场景，其中包含几个 <code>@Configuration</code>类，每个类都取决于其他类中声明的bean：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ServiceConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransferService <span class="title">transferService</span><span class="params">(AccountRepository accountRepository)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TransferServiceImpl(accountRepository);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RepositoryConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> AccountRepository <span class="title">accountRepository</span><span class="params">(DataSource dataSource)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> JdbcAccountRepository(dataSource);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Import</span>(&#123;ServiceConfig<span class="class">.<span class="keyword">class</span>, <span class="title">RepositoryConfig</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class"><span class="title">public</span> <span class="title">class</span> <span class="title">SystemTestConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// return new DataSource</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ApplicationContext ctx = <span class="keyword">new</span> AnnotationConfigApplicationContext(SystemTestConfig<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    <span class="comment">// everything wires up across configuration classes...</span></span><br><span class="line">    TransferService transferService = ctx.getBean(TransferService<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    transferService.transfer(<span class="number">100.00</span>, <span class="string">"A123"</span>, <span class="string">"C456"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>还有另一种方法可以达到相同的效果。请记住，<code>@Configuration</code>类最终只是容器中的另一个bean： 这意味着它们可以利用<code>@Autowired</code> 和 <code>@Value</code> 注入以及与任何其他bean相同的其他功能。</p>
<p>确保以这种方式注入的依赖项只是最简单的。<code>@Configuration</code>类在上下文初始化期间很早就被处理，并且强制以这种方式注入依赖项可能会导致意外的早期初始化。 尽可能采用基于参数的注入，如前面的示例所示。</p>
<p>另外，要特别注意通过<code>@Bean</code>的<code>BeanPostProcessor</code> 和 <code>BeanFactoryPostProcessor</code>定义。 这些通常应该声明为静态<code>@Bean</code>方法，而不是触发其包含配置类的实例化。否则，<code>@Autowired</code> 和 <code>@Value</code>不能在配置类本身上工作，因为它过早地被创建为bean实例。</p>
<p>以下示例显示了如何将一个bean自动连接到另一个bean:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ServiceConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> AccountRepository accountRepository;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransferService <span class="title">transferService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TransferServiceImpl(accountRepository);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RepositoryConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> DataSource dataSource;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">RepositoryConfig</span><span class="params">(DataSource dataSource)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.dataSource = dataSource;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> AccountRepository <span class="title">accountRepository</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> JdbcAccountRepository(dataSource);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Import</span>(&#123;ServiceConfig<span class="class">.<span class="keyword">class</span>, <span class="title">RepositoryConfig</span>.<span class="title">class</span>&#125;)</span></span><br><span class="line"><span class="class"><span class="title">public</span> <span class="title">class</span> <span class="title">SystemTestConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// return new DataSource</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ApplicationContext ctx = <span class="keyword">new</span> AnnotationConfigApplicationContext(SystemTestConfig<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    <span class="comment">// everything wires up across configuration classes...</span></span><br><span class="line">    TransferService transferService = ctx.getBean(TransferService<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    transferService.transfer(<span class="number">100.00</span>, <span class="string">"A123"</span>, <span class="string">"C456"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>仅在Spring Framework 4.3中支持<code>@Configuration</code>类中的构造函数注入。 另请注意，如果目标bean仅定义了一个构造函数，则无需指定<code>@Autowired</code>。 在前面的示例中，<code>RepositoryConfig</code>构造函数中不需要<code>@Autowired</code>。</p>
<p>完全导入bean便于查找</p>
<p>在上面的场景中,<code>@Autowired</code>可以很好的工作,使设计更具模块化,但是自动注入哪个bean依然有些模糊不清.例如, 作为一个开发者查看<code>ServiceConfig</code>类时,你怎么知道<code>@Autowired AccountRepository</code>在哪定义的呢?代码中并未明确指出, 还好, <a href="https://spring.io/tools/sts" target="_blank" rel="noopener">Spring Tool Suite</a>提供的工具可以呈现图表，显示所有内容的连线方式，这可能就是您所需要的。 此外，您的Java IDE可以轻松找到<code>AccountRepository</code>类型的所有声明和用法，并快速显示返回该类型的<code>@Bean</code>方法的位置。</p>
<p>万一需求不允许这种模糊的装配,并且您希望从IDE中从一个<code>@Configuration</code>类直接导航到另一个<code>@Configuration</code>类，请考虑自动装配配置类本身。 以下示例显示了如何执行此操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ServiceConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RepositoryConfig repositoryConfig;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransferService <span class="title">transferService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// navigate 'through' the config class to the @Bean method!</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TransferServiceImpl(repositoryConfig.accountRepository());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在前面的情况中，定义<code>AccountRepository</code> 是完全明确的。但是，<code>ServiceConfig</code>现在与<code>RepositoryConfig</code>紧密耦合。这是一种权衡的方法。 通过使用基于接口的或基于类的抽象<code>@Configuration</code> 类，可以在某种程度上减轻这种紧密耦合。请考虑以下示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ServiceConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RepositoryConfig repositoryConfig;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransferService <span class="title">transferService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TransferServiceImpl(repositoryConfig.accountRepository());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">RepositoryConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function">AccountRepository <span class="title">accountRepository</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultRepositoryConfig</span> <span class="keyword">implements</span> <span class="title">RepositoryConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> AccountRepository <span class="title">accountRepository</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> JdbcAccountRepository(...);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Import</span>(&#123;ServiceConfig<span class="class">.<span class="keyword">class</span>, <span class="title">DefaultRepositoryConfig</span>.<span class="title">class</span>&#125;)  // <span class="title">import</span> <span class="title">the</span> <span class="title">concrete</span> <span class="title">config</span>!</span></span><br><span class="line"><span class="class"><span class="title">public</span> <span class="title">class</span> <span class="title">SystemTestConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// return DataSource</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    ApplicationContext ctx = <span class="keyword">new</span> AnnotationConfigApplicationContext(SystemTestConfig<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    TransferService transferService = ctx.getBean(TransferService<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    transferService.transfer(<span class="number">100.00</span>, <span class="string">"A123"</span>, <span class="string">"C456"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在，<code>ServiceConfig</code>与具体的<code>DefaultRepositoryConfig</code>松散耦合，内置的IDE工具仍然很有用：您可以很容易获取<code>RepositoryConfig</code>实现类的继承体系。 以这种方式,操作<code>@Configuration</code>类及其依赖关系与操作基于接口的代码的过程没有什么区别</p>
<p>如果要影响某些bean的启动创建顺序，可以考虑将其中一些声明为<code>@Lazy</code> （用于在首次访问时创建而不是在启动时）或<code>@DependsOn</code>某些其他bean（确保在创建之前创建特定的其他bean（当前的bean，超出后者的直接依赖性所暗示的））。</p>
<p><a id="beans-java-conditional"></a></p>
<h5 id="有条件地包含-Configuration类或-Bean方法"><a href="#有条件地包含-Configuration类或-Bean方法" class="headerlink" title="有条件地包含@Configuration类或@Bean方法"></a><a href="#beans-java-conditional"></a>有条件地包含<code>@Configuration</code>类或<code>@Bean</code>方法</h5><p>基于某些任意系统状态，有条件地启用或禁用完整的<code>@Configuration</code>类甚至单独的 <code>@Bean</code> 方法通常很有用。 一个常见的例子是， 只有在Spring环境中启用了特定的配置文件时才使用<code>@Profile</code> 注解来激活bean（有关详细信息，请参阅Bean<a href="#beans-definition-profiles">定义配置文件</a>）。</p>
<p><code>@Profile</code>注解实际上是通过使用更灵活的注解<code>@Conditional</code>实现的。<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/annotation/Conditional.html" target="_blank" rel="noopener"><code>@Conditional</code></a>注解表示特定的<code>org.springframework.context.annotation.Condition</code>实现。 它表明<code>@Bean</code>被注册之前会先”询问”<code>@Conditional</code>注解。</p>
<p><code>Condition</code>接口的实现提供了一个返回<code>true</code> 或 <code>false</code>的<code>matches(…)</code>方法。例如，以下清单显示了用于 <code>@Profile</code>的实际<code>Condition</code>实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">matches</span><span class="params">(ConditionContext context, AnnotatedTypeMetadata metadata)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (context.getEnvironment() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// Read the @Profile annotation attributes</span></span><br><span class="line">        MultiValueMap&lt;String, Object&gt; attrs = metadata.getAllAnnotationAttributes(Profile<span class="class">.<span class="keyword">class</span>.<span class="title">getName</span>())</span>;</span><br><span class="line">        <span class="keyword">if</span> (attrs != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">for</span> (Object value : attrs.get(<span class="string">"value"</span>)) &#123;</span><br><span class="line">                <span class="keyword">if</span> (context.getEnvironment().acceptsProfiles(((String[]) value))) &#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>有关更多详细信息，请参阅<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/annotation/Conditional.html" target="_blank" rel="noopener"><code>@Conditional</code></a>javadoc。</p>
<p><a id="beans-java-combining"></a></p>
<h5 id="结合Java和XML配置"><a href="#结合Java和XML配置" class="headerlink" title="结合Java和XML配置"></a><a href="#beans-java-combining"></a>结合Java和XML配置</h5><p>Spring的<code>@Configuration</code>类支持但不一定成为Spring XML的100％完全替代品。 某些工具（如Spring XML命名空间）仍然是配置容器的理想方法。在XML方便或必要的情况下，您可以选择：通过使用例如<code>ClassPathXmlApplicationContext</code>以“以XML为中心”的方式实例化容器， 或者通过使用<code>AnnotationConfigApplicationContext</code>以“以Java为中心”的方式实例化它。<code>@ImportResource</code>注解，根据需要导入XML。</p>
<p><a id="beans-java-combining-xml-centric"></a></p>
<h6 id="以XML为中心使用-Configuration类"><a href="#以XML为中心使用-Configuration类" class="headerlink" title="以XML为中心使用@Configuration类"></a><a href="#beans-java-combining-xml-centric"></a>以XML为中心使用<code>@Configuration</code>类</h6><p>更受人喜爱的方法是从包含<code>@Configuration</code>类的XML启动容器.例如，在使用Spring的现有系统中,大量使用的是Spring XML配置,所以很容易根据需要创建<code>@Configuration</code>类 ,并将他们到包含XML文件中。我们将介绍在这种“以XML为中心”的情况下使用<code>@Configuration</code>类的选项。</p>
<p>将<code>@Configuration</code>类声明为普通的Spring<code>&lt;bean/&gt;</code> 元素</p>
<p>请记住,<code>@Configuration</code>类最终也只是容器中的bean定义。在本系列示例中，我们创建一个名为AppConfig的<code>@Configuration</code>类，并将其作为<code>&lt;bean/&gt;</code>定义包含在<code>system-test-config.xml</code>中。 由于 <code>&lt;context:annotation-config/&gt;</code>已打开，容器会识别<code>@Configuration</code> 注解并正确处理<code>AppConfig</code>中声明的<code>@Bean</code> 方法。</p>
<p>以下示例显示了Java中的普通配置类:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> DataSource dataSource;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> AccountRepository <span class="title">accountRepository</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> JdbcAccountRepository(dataSource);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TransferService <span class="title">transferService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> TransferService(accountRepository());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以下示例显示了示例<code>system-test-config.xml</code>文件的一部分：</p>
<pre><code>&lt;beans&gt;
    &lt;!-- enable processing of annotations such as @Autowired and @Configuration --&gt;
    &lt;context:annotation-config/&gt;
    &lt;context:property-placeholder location=&quot;classpath:/com/acme/jdbc.properties&quot;/&gt;

    &lt;bean class=&quot;com.acme.AppConfig&quot;/&gt;

    &lt;bean class=&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;&gt;
        &lt;property name=&quot;url&quot; value=&quot;${jdbc.url}&quot;/&gt;
        &lt;property name=&quot;username&quot; value=&quot;${jdbc.username}&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;${jdbc.password}&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;</code></pre><p>以下示例显示了可能的<code>jdbc.properties</code>文件:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">jdbc.url&#x3D;jdbc:hsqldb:hsql:&#x2F;&#x2F;localhost&#x2F;xdb</span><br><span class="line">jdbc.username&#x3D;sa</span><br><span class="line">jdbc.password&#x3D;</span><br></pre></td></tr></table></figure>



<pre><code>public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;classpath:/com/acme/system-test-config.xml&quot;);
    TransferService transferService = ctx.getBean(TransferService.class);
    // ...
}</code></pre><p>在 <code>system-test-config.xml</code>文件中， <code>AppConfig</code> <code>&lt;bean/&gt;</code>不声明<code>id</code>元素。虽然这样做是可以的，但是没有必要，因为没有其他bean引用它，并且不太可能通过名称从容器中明确地获取它。 类似地，<code>DataSource</code> bean只是按类型自动装配，因此不严格要求显式的bean<code>id</code>。</p>
<p>使用<a href="context:component-scan/">context:component-scan/</a> 来获取<code>@Configuration</code> 类</p>
<p>因为<code>@Configuration</code>是<code>@Component</code>注解的元注解,所以<code>@Configuration</code>注解的类也可以被自动扫描。使用与上面相同的场景，可以重新定义<code>system-test-config.xml</code> 以使用组件扫描。 请注意，在这种情况下，我们不需要显式声明 <code>&lt;context:annotation-config/&gt;</code>,，因为<code>&lt;context:component-scan/&gt;</code> 启用相同的功能。</p>
<p>以下示例显示了已修改的<code>system-test-config.xml</code>文件:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- picks up and registers AppConfig as a bean definition --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:component-scan</span> <span class="attr">base-package</span>=<span class="string">"com.acme"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:property-placeholder</span> <span class="attr">location</span>=<span class="string">"classpath:/com/acme/jdbc.properties"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"url"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.url&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.username&#125;"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"$&#123;jdbc.password&#125;"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><a id="beans-java-combining-java-centric"></a></p>
<h6 id="基于-Configuration混合XML的-ImportResource"><a href="#基于-Configuration混合XML的-ImportResource" class="headerlink" title="基于@Configuration混合XML的@ImportResource"></a><a href="#beans-java-combining-java-centric"></a>基于<code>@Configuration</code>混合XML的<code>@ImportResource</code></h6><p>在 <code>@Configuration</code>类为配置容器的主要方式的应用程序中,也需要使用一些XML配置。在这些情况下,只需使用<code>@ImportResource</code> ,并只定义所需的XML。这样做可以实现“以Java为中心”的方法来配置容器并尽可能少的使用XML。 以下示例（包括配置类，定义bean的XML文件，属性文件和主类）显示了如何使用<code>@ImportResource</code> 注解来实现根据需要使用XML的“以Java为中心”的配置：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ImportResource</span>(<span class="string">"classpath:/com/acme/properties-config.xml"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;jdbc.url&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String url;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;jdbc.username&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String username;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;jdbc.password&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DriverManagerDataSource(url, username, password);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">properties-config.xml</span><br><span class="line">&lt;beans&gt;</span><br><span class="line">    &lt;context:property-placeholder location=<span class="string">"classpath:/com/acme/jdbc.properties"</span>/&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">jdbc.properties</span><br><span class="line">jdbc.url&#x3D;jdbc:hsqldb:hsql:&#x2F;&#x2F;localhost&#x2F;xdb</span><br><span class="line">jdbc.username&#x3D;sa</span><br><span class="line">jdbc.password&#x3D;</span><br></pre></td></tr></table></figure>



<pre><code>public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    TransferService transferService = ctx.getBean(TransferService.class);
    // ...
}</code></pre><p><a id="beans-environment"></a></p>
<h3 id="1-13-抽象环境"><a href="#1-13-抽象环境" class="headerlink" title="1.13. 抽象环境"></a><a href="#beans-environment"></a>1.13. 抽象环境</h3><p><a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/core/env/Environment.html" target="_blank" rel="noopener"><code>Environment</code></a>接口是集成在容器中的抽象，它模拟了应用程序环境的两个关键方面：<a href="#beans-definition-profiles">profiles</a> 和 <a href="#beans-property-source-abstraction">properties</a>。</p>
<p>profile配置是一个被命名的,bean定义的逻辑组,这些bean只有在给定的profile配置激活时才会注册到容器.无论是以XML还是通过注解定义,Bean都可以分配给配置文件 。<code>Environment</code>对象在profile中的角色是判断哪一个profile应该在当前激活和哪一个profile应该在默认情况下激活。</p>
<p>属性在几乎所有应用程序中都发挥着重要作用，可能源自各种源：属性文件，JVM系统属性，系统环境变量，JNDI，servlet上下文参数，ad-hoc属性对象，Map对象等。 与属性相关的<code>Environment</code>对象的作用是为用户提供方便的服务接口，用于配置属性源和从中解析属性。</p>
<p><a id="beans-definition-profiles"></a></p>
<h4 id="1-13-1-Bean定义Profiles"><a href="#1-13-1-Bean定义Profiles" class="headerlink" title="1.13.1. Bean定义Profiles"></a><a href="#beans-definition-profiles"></a>1.13.1. Bean定义Profiles</h4><p>bean定义profiles是核心容器内的一种机制，该机制能在不同环境中注册不同的bean。“环境”这个词对不同的用户来说意味着不同的东西，这个功能可以帮助解决许多用例，包括：</p>
<ul>
<li><p>在QA或生产环境中，针对开发中的内存数据源而不是从JNDI查找相同的数据源。</p>
</li>
<li><p>开发期使用监控组件，当部署以后则关闭监控组件，使应用更高效</p>
</li>
<li><p>为用户各自注册自定义bean实现</p>
</li>
</ul>
<p>考虑<code>DataSource</code>的实际应用程序中的第一个用例。 在测试环境中，配置可能类似于以下内容：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> EmbeddedDatabaseBuilder()</span><br><span class="line">        .setType(EmbeddedDatabaseType.HSQL)</span><br><span class="line">        .addScript(<span class="string">"my-schema.sql"</span>)</span><br><span class="line">        .addScript(<span class="string">"my-test-data.sql"</span>)</span><br><span class="line">        .build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在考虑如何将此应用程序部署到QA或生产环境中，假设应用程序的数据源已注册到生产应用程序服务器的JNDI目录。 我们的<code>dataSource</code> bean现在看起来如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span>(destroyMethod=<span class="string">""</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    Context ctx = <span class="keyword">new</span> InitialContext();</span><br><span class="line">    <span class="keyword">return</span> (DataSource) ctx.lookup(<span class="string">"java:comp/env/jdbc/datasource"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>问题是如何根据当前环境在使用这两种变体之间切换。随着时间的推移，Spring用户已经设计了许多方法来完成这项工作，通常依赖于系统环境变量和包含<code>${placeholder}</code>标记的XML<code>&lt;import/&gt;</code>语句的组合， 这些标记根据值解析为正确的配置文件路径一个环境变量。 Bean定义profiles是核心容器功能，可为此问题提供解决方案。</p>
<p>概括一下上面的场景，环境决定bean定义,最后发现,我们需要在某些上下文环境中使用某些bean,在其他环境中则不用这些bean.或者说, 在场景A中注册一组bean定义,而在场景B中注册另外一组。先看看如何通过修改配置来完成此需求：</p>
<p><a id="beans-definition-profiles-java"></a></p>
<h5 id="使用-Profile"><a href="#使用-Profile" class="headerlink" title="使用 @Profile"></a><a href="#beans-definition-profiles-java"></a>使用 <code>@Profile</code></h5><p><a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/annotation/Profile.html" target="_blank" rel="noopener"><code>@Profile</code></a>注解用于当一个或多个配置文件激活的时候,用来指定组件是否有资格注册。使用前面的示例，我们可以重写<code>dataSource</code>配置，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Profile</span>(<span class="string">"development"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StandaloneDataConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> EmbeddedDatabaseBuilder()</span><br><span class="line">            .setType(EmbeddedDatabaseType.HSQL)</span><br><span class="line">            .addScript(<span class="string">"classpath:com/bank/config/sql/schema.sql"</span>)</span><br><span class="line">            .addScript(<span class="string">"classpath:com/bank/config/sql/test-data.sql"</span>)</span><br><span class="line">            .build();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Profile</span>(<span class="string">"production"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JndiDataConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(destroyMethod=<span class="string">""</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Context ctx = <span class="keyword">new</span> InitialContext();</span><br><span class="line">        <span class="keyword">return</span> (DataSource) ctx.lookup(<span class="string">"java:comp/env/jdbc/datasource"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如前所述，使用<code>@Bean</code>方法，您通常选择使用Spring的<code>JndiTemplate</code>/<code>JndiLocatorDelegate</code>帮助程序或前面显示的 直接JNDI <code>InitialContext</code>用法但不使用<code>JndiObjectFactoryBean</code>变量来使用编程JNDI查找，这会强制您将返回类型声明为 <code>FactoryBean</code>类型。 As mentioned earlier, with <code>@Bean</code> methods, you typically choose to use programmatic JNDI lookups, by using either Spring’s <code>JndiTemplate</code>/<code>JndiLocatorDelegate</code> helpers or the straight JNDI <code>InitialContext</code> usage shown earlier but not the <code>JndiObjectFactoryBean</code> variant, which would force you to declare the return type as the <code>FactoryBean</code> type.</p>
<p>profile字符串可以包含简单的profile名称（例如，<code>production</code>）或profile表达式。 profile表达式允许表达更复杂的概要逻辑（例如，<code>production &amp; us-east</code>）。 profile表达式支持以下运算符：</p>
<ul>
<li><p><code>!</code>: A logical “not” of the profile</p>
</li>
<li><p><code>&amp;</code>: A logical “and” of the profiles</p>
</li>
<li><p><code>|</code>: A logical “or” of the profiles</p>
</li>
</ul>
<p>你不能不使用括号而混合 <code>&amp;</code> 和 <code>|</code> 。 例如，<code>production &amp; us-east | eu-central</code>不是一个有效的表达。 它必须表示为 <code>production &amp; (us-east | eu-central)</code>.。</p>
<p>您可以将<code>@Profile</code>用作<a href="#beans-meta-annotations">元注解</a>，以创建自定义组合注解。 以下示例定义了一个自定义<code>@Production</code>注解，您可以将其用作<code>@Profile(&quot;production&quot;)</code>的替代品：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(ElementType.TYPE)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Profile</span>(<span class="string">"production"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Production &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果<code>@Configuration</code>类标有 <code>@Profile</code>,类中所有<code>@Bean</code>和<code>@Import</code>注解相关的类都将被忽略,除非该profile被激活。 如果一个<code>@Component</code>或<code>@Configuration</code>类被标记为<code>@Profile({&quot;p1&quot;, &quot;p2&quot;})</code>。那么除非profile ‘p1’ or ‘p2’ 已被激活。 否则该类将不会注册/处理。如果给定的配置文件以NOT运算符(<code>!</code>)为前缀，如果配置文件为not active，则注册的元素将被注册。 例如，给定<code>@Profile({&quot;p1&quot;, &quot;!p2&quot;})</code>，如果配置文件“p1”处于活动状态或配置文件“p2”未激活，则会进行注册。</p>
<p><code>@Profile</code>也能注解方法，用于配置一个配置类中的指定bean。如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(<span class="string">"dataSource"</span>)</span><br><span class="line">    <span class="meta">@Profile</span>(<span class="string">"development"</span>) (<span class="number">1</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">standaloneDataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> EmbeddedDatabaseBuilder()</span><br><span class="line">            .setType(EmbeddedDatabaseType.HSQL)</span><br><span class="line">            .addScript(<span class="string">"classpath:com/bank/config/sql/schema.sql"</span>)</span><br><span class="line">            .addScript(<span class="string">"classpath:com/bank/config/sql/test-data.sql"</span>)</span><br><span class="line">            .build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span>(<span class="string">"dataSource"</span>)</span><br><span class="line">    <span class="meta">@Profile</span>(<span class="string">"production"</span>) (<span class="number">2</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">jndiDataSource</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Context ctx = <span class="keyword">new</span> InitialContext();</span><br><span class="line">        <span class="keyword">return</span> (DataSource) ctx.lookup(<span class="string">"java:comp/env/jdbc/datasource"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>1</strong>、<code>standaloneDataSource</code> 方法仅在 <code>development</code> 环境可用.</p>
<p><strong>2</strong>、<code>jndiDataSource</code>方法仅在 <code>production</code> 环境可用.</p>
<p>在<code>@Bean</code> 方法上还添加有<code>@Profile</code>注解,可能会应用在特殊情况。在相同Java方法名称的重载<code>@Bean</code>方法(类似于构造函数重载）的情况下， 需要在所有重载方法上一致声明<code>@Profile</code>条件，如果条件不一致，则只有重载方法中第一个声明的条件才重要。因此，<code>@Profile</code>不能用于选择具有特定参数签名的重载方法， 所有工厂方法对相同的bean在Spring构造器中的解析算法在创建时是相同的。</p>
<p>如果想定义具有不同配置文件条件的备用bean，请使用不同的Java方法名称，通过<code>@Bean</code>名称属性指向相同的bean名称。如上例所示。 如果参数签名都是相同的（例如，所有的变体都是无参的工厂方法），这是安排有效Java类放在首要位置的唯一方法（因为只有一个 特定名称和参数签名的方法）。</p>
<p><a id="beans-definition-profiles-xml"></a></p>
<h5 id="XML-bean定义profiles"><a href="#XML-bean定义profiles" class="headerlink" title="XML bean定义profiles"></a><a href="#beans-definition-profiles-xml"></a>XML bean定义profiles</h5><p>XML中的<code>&lt;beans&gt;</code> 元素有一个<code>profile</code> 属性,我们之前的示例配置可以在两个XML文件中重写，如下所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">profile</span>=<span class="string">"development"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:jdbc</span>=<span class="string">"http://www.springframework.org/schema/jdbc"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"..."</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">jdbc:embedded-database</span> <span class="attr">id</span>=<span class="string">"dataSource"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">jdbc:script</span> <span class="attr">location</span>=<span class="string">"classpath:com/bank/config/sql/schema.sql"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">jdbc:script</span> <span class="attr">location</span>=<span class="string">"classpath:com/bank/config/sql/test-data.sql"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">jdbc:embedded-database</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">profile</span>=<span class="string">"production"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:jee</span>=<span class="string">"http://www.springframework.org/schema/jee"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"..."</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">jee:jndi-lookup</span> <span class="attr">id</span>=<span class="string">"dataSource"</span> <span class="attr">jndi-name</span>=<span class="string">"java:comp/env/jdbc/datasource"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>也可以不用分开2个文件，在同一个XML中配置2个<code>&lt;beans/&gt;</code>，<code>&lt;beans/&gt;</code>元素也有profile属性。如以下示例所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:jdbc</span>=<span class="string">"http://www.springframework.org/schema/jdbc"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:jee</span>=<span class="string">"http://www.springframework.org/schema/jee"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"..."</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- other bean definitions --&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">beans</span> <span class="attr">profile</span>=<span class="string">"development"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">jdbc:embedded-database</span> <span class="attr">id</span>=<span class="string">"dataSource"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">jdbc:script</span> <span class="attr">location</span>=<span class="string">"classpath:com/bank/config/sql/schema.sql"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">jdbc:script</span> <span class="attr">location</span>=<span class="string">"classpath:com/bank/config/sql/test-data.sql"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">jdbc:embedded-database</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">beans</span> <span class="attr">profile</span>=<span class="string">"production"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">jee:jndi-lookup</span> <span class="attr">id</span>=<span class="string">"dataSource"</span> <span class="attr">jndi-name</span>=<span class="string">"java:comp/env/jdbc/datasource"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>spring-bean.xsd</code> 强制允许将profile元素定义在文件的最后面，这有助于在XML文件中提供灵活的方式而又不引起混乱。</p>
<p>对应XML不支持前面描述的profile表达式。 但是，有可能通过使用<code>!</code> 来否定一个profile表达式。 也可以通过嵌套profiles来应用“and”，如以下示例所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:jdbc</span>=<span class="string">"http://www.springframework.org/schema/jdbc"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:jee</span>=<span class="string">"http://www.springframework.org/schema/jee"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">"..."</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- other bean definitions --&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">beans</span> <span class="attr">profile</span>=<span class="string">"production"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">beans</span> <span class="attr">profile</span>=<span class="string">"us-east"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">jee:jndi-lookup</span> <span class="attr">id</span>=<span class="string">"dataSource"</span> <span class="attr">jndi-name</span>=<span class="string">"java:comp/env/jdbc/datasource"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在前面的示例中，如果<code>production</code> 和<code>us-east</code> profiles都处于活动状态，则会暴露<code>dataSource</code> bean。</p>
<p><a id="beans-definition-profiles-enable"></a></p>
<h5 id="启用profile"><a href="#启用profile" class="headerlink" title="启用profile"></a><a href="#beans-definition-profiles-enable"></a>启用profile</h5><p>现在已经更新了配置,但仍然需要指定要激活哪个配置文件, 如果我们现在开始我们的示例应用程序， 我们会看到抛出<code>NoSuchBeanDefinitionException</code>，因为容器找不到名为<code>dataSource</code>的Spring bean。</p>
<p>激活配置文件可以通过多种方式完成，但最直接的方法是以编程方式对可通过<code>ApplicationContext</code>提供的<code>Environment</code> API进行操作。 以下示例显示了如何执行此操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">AnnotationConfigApplicationContext ctx = <span class="keyword">new</span> AnnotationConfigApplicationContext();</span><br><span class="line">ctx.getEnvironment().setActiveProfiles(<span class="string">"development"</span>);</span><br><span class="line">ctx.register(SomeConfig<span class="class">.<span class="keyword">class</span>, <span class="title">StandaloneDataConfig</span>.<span class="title">class</span>, <span class="title">JndiDataConfig</span>.<span class="title">class</span>)</span>;</span><br><span class="line">ctx.refresh();</span><br></pre></td></tr></table></figure>

<p>此外,配置文件也可以通过<code>spring.profiles.active</code>属性声明式性地激活,可以通过系统环境变量，JVM系统属性，<code>web.xml</code>中的Servlet上下文参数指定， 甚至作为JNDI中的一个条目设置（<a href="#beans-property-source-abstraction"><code>PropertySource</code> 抽象</a>）。在集成测试中，可以通过 <code>spring-test</code>模块中的<code>@ActiveProfiles</code>注解来声明活动配置文件(参见使用<a href="https://github.com/DocsHome/spring-docs/blob/master/pages/test/testing.mdl#testcontext-ctx-management-env-profiles" target="_blank" rel="noopener">环境配置文件的上下文配置</a>)</p>
<p>配置文件不是“二选一”的。开发者可以一次激活多个配置文件。使用编程方式，您可以为<code>setActiveProfiles()</code>方法提供多个配置文件名称，该方法接受 <code>String…</code>varargs。 以下示例激活多个配置文件：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ctx.getEnvironment().setActiveProfiles(<span class="string">"profile1"</span>, <span class="string">"profile2"</span>);</span><br></pre></td></tr></table></figure>

<p>声明性地，<code>spring.profiles.active</code>可以接受以逗号分隔的profile名列表，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-Dspring.profiles.active=<span class="string">"profile1,profile2"</span></span><br></pre></td></tr></table></figure>

<p><a id="beans-definition-profiles-default"></a></p>
<h5 id="默认-Profile"><a href="#默认-Profile" class="headerlink" title="默认 Profile"></a><a href="#beans-definition-profiles-default"></a>默认 Profile</h5><p>default配置文件表示默认开启的profile配置。考虑以下配置:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Profile</span>(<span class="string">"default"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultDataConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> EmbeddedDatabaseBuilder()</span><br><span class="line">            .setType(EmbeddedDatabaseType.HSQL)</span><br><span class="line">            .addScript(<span class="string">"classpath:com/bank/config/sql/schema.sql"</span>)</span><br><span class="line">            .build();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果没有配置文件激活，上面的<code>dataSource</code>就会被创建。这提供了一种默认的方式，如果有任何一个配置文件启用，default配置就不会生效。</p>
<p>默认配置文件的名字(default）可以通过<code>Environment</code>的<code>setDefaultProfiles()</code>方法或者<code>spring.profiles.default</code>属性修改。</p>
<p><a id="beans-property-source-abstraction"></a></p>
<h4 id="1-13-2-PropertySource-抽象"><a href="#1-13-2-PropertySource-抽象" class="headerlink" title="1.13.2. PropertySource 抽象"></a><a href="#beans-property-source-abstraction"></a>1.13.2. <code>PropertySource</code> 抽象</h4><p>Spring的<code>Environment</code>抽象提供用于一系列的propertysources属性配置文件的搜索操作.请考虑以下列表：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ApplicationContext ctx = <span class="keyword">new</span> GenericApplicationContext();</span><br><span class="line">Environment env = ctx.getEnvironment();</span><br><span class="line"><span class="keyword">boolean</span> containsMyProperty = env.containsProperty(<span class="string">"my-property"</span>);</span><br><span class="line">System.out.println(<span class="string">"Does my environment contain the 'my-property' property? "</span> + containsMyProperty);</span><br></pre></td></tr></table></figure>

<p>在上面的代码段中,一个高级别的方法用于访问Spring是否为当前环境定义了<code>my-property</code> 属性。为了回答这个问题，<code>Environment</code>对象对一组PropertySource对象进行搜索。 <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/core/env/PropertySource.html" target="_blank" rel="noopener"><code>PropertySource</code></a>是对任何键值对的简单抽象，Spring的<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/core/env/StandardEnvironment.html" target="_blank" rel="noopener"><code>StandardEnvironment</code></a>配置有两个<code>PropertySource</code>对象 ，一个表示JVM系统属性(<code>System.getProperties()</code>),一个表示系统环境变量(<code>System.getenv()</code>)。</p>
<p>这些默认property源位于<code>StandardEnvironment</code>中,用于独立应用程序。<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/web/context/support/StandardServletEnvironment.html" target="_blank" rel="noopener"><code>StandardServletEnvironment</code></a>用默认的property配置源填充。 默认配置源包括Servlet配置和Servlet上下文参数，它可以选择启用<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/jndi/JndiPropertySource.html" target="_blank" rel="noopener"><code>JndiPropertySource</code></a>。有关详细信息，请参阅它的javadocs</p>
<p>具体地说，当您使用<code>StandardEnvironment</code>时，如果在运行时存在<code>my-property</code>系统属性或<code>my-propertyi</code>环境变量，则对 <code>env.containsProperty(&quot;my-property&quot;)</code>的调用将返回true。</p>
<p>执行的搜索是分层的。默认情况下，系统属性优先于环境变量，因此如果在调用<code>env.getProperty(&quot;my-property&quot;)</code>期间碰巧在两个位置都设置了<code>my-property</code>属性， 系统属性值返回优先于环境变量。 请注意，属性值未合并，而是由前面的条目完全覆盖。</p>
<p>对于常见的 <code>StandardServletEnvironment</code>，完整层次结构如下，最高优先级条目位于顶部：</p>
<ol>
<li><p>ServletConfig参数（如果适用 - 例如，在DispatcherServlet上下文的情况下）</p>
</li>
<li><p>ServletContext参数（web.xml context-param条目）</p>
</li>
<li><p>JNDI环境变量（<code>java:comp/env/</code>entries）</p>
</li>
<li><p>JVM系统属性（<code>-D</code>命令行参数）</p>
</li>
<li><p>JVM系统环境（操作系统环境变量）</p>
</li>
</ol>
<p>最重要的是,整个机制都是可配置的。也许开发者需要一个自定义的properties源，并将该源整合到这个检索层级中。为此，请实现并实例化您自己的<code>PropertySource</code>，并将其添加到当前<code>Environment</code>的<code>PropertySource</code>集合中。 以下示例显示了如何执行此操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ConfigurableApplicationContext ctx = <span class="keyword">new</span> GenericApplicationContext();</span><br><span class="line">MutablePropertySources sources = ctx.getEnvironment().getPropertySources();</span><br><span class="line">sources.addFirst(<span class="keyword">new</span> MyPropertySource());</span><br></pre></td></tr></table></figure>

<p>在上面的代码中， <code>MyPropertySource</code>在搜索中添加了最高优先级。如果它包含<code>my-property</code>属性，则会检测并返回该属性， 优先于其他 <code>PropertySource</code>中的任何<code>my-property</code>属性。 <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/core/env/MutablePropertySources.html" target="_blank" rel="noopener"><code>MutablePropertySources</code></a> API公开了许多方法，允许你显式操作property属性源。</p>
<p><a id="beans-using-propertysource"></a></p>
<h4 id="1-13-3-使用-PropertySource"><a href="#1-13-3-使用-PropertySource" class="headerlink" title="1.13.3. 使用 @PropertySource"></a><a href="#beans-using-propertysource"></a>1.13.3. 使用 <code>@PropertySource</code></h4><p><a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/annotation/PropertySource.html" target="_blank" rel="noopener"><code>@PropertySource</code></a> 注解提供了便捷的方式，用于增加<code>PropertySource</code>到Spring的 <code>Environment</code>中。</p>
<p>给定一个名为<code>app.properties</code>的文件，其中包含键值对<code>testbean.name=myTestBean</code>， 以下<code>@Configuration</code>类使用<code>@PropertySource</code>，以便调用<code>testBean.getName()</code> 返回<code>myTestBean</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@PropertySource</span>(<span class="string">"classpath:/com/myco/app.properties"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    Environment env;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TestBean <span class="title">testBean</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        TestBean testBean = <span class="keyword">new</span> TestBean();</span><br><span class="line">        testBean.setName(env.getProperty(<span class="string">"testbean.name"</span>));</span><br><span class="line">        <span class="keyword">return</span> testBean;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>任何的存在于<code>@PropertySource</code>中的<code>${…}</code>占位符，将会被解析为定义在环境中的属性配置文件中的属性值。 如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@PropertySource</span>(<span class="string">"classpath:/com/$&#123;my.placeholder:default/path&#125;/app.properties"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    Environment env;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TestBean <span class="title">testBean</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        TestBean testBean = <span class="keyword">new</span> TestBean();</span><br><span class="line">        testBean.setName(env.getProperty(<span class="string">"testbean.name"</span>));</span><br><span class="line">        <span class="keyword">return</span> testBean;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>假设<code>my.placeholder</code>存在于已注册的其中一个属性源中（例如，系统属性或环境变量），则占位符将解析为相应的值。 如果不是，则<code>default/path</code>用作默认值。 如果未指定默认值且无法解析属性，则抛出<code>IllegalArgumentException</code>。</p>
<p>根据Java 8惯例，<code>@PropertySource</code>注解是可重复的。 但是，所有这些<code>@PropertySource</code>注解都需要在同一级别声明，可以直接在配置类上声明， 也可以在同一自定义注解中作为元注解声明。 不建议混合直接注解和元注解，因为直接注解有效地覆盖了元注解。</p>
<p><a id="beans-placeholder-resolution-in-statements"></a></p>
<h4 id="1-13-4-在声明中的占位符"><a href="#1-13-4-在声明中的占位符" class="headerlink" title="1.13.4. 在声明中的占位符"></a><a href="#beans-placeholder-resolution-in-statements"></a>1.13.4. 在声明中的占位符</h4><p>之前，元素中占位符的值只能针对JVM系统属性或环境变量进行解析。现在已经打破了这种情况。因为环境抽象集成在整个容器中，所以很容易通过它来对占位符进行解析. 这意味着开发者可以以任何喜欢的方式来配置这个解析过程，可以改变是优先查找系统properties或者是有限查找环境变量，或者删除它们；增加自定义property源，使之成为更合适的配置</p>
<p>具体而言，只要在<code>Environment</code>中可用，无论<code>customer</code>属性在何处定义，以下语句都可以工作：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">import</span> <span class="attr">resource</span>=<span class="string">"com/bank/service/$&#123;customer&#125;-config.xml"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><a id="context-load-time-weaver"></a></p>
<h3 id="1-14-注册LoadTimeWeaver"><a href="#1-14-注册LoadTimeWeaver" class="headerlink" title="1.14. 注册LoadTimeWeaver"></a><a href="#context-load-time-weaver"></a>1.14. 注册<code>LoadTimeWeaver</code></h3><p><code>LoadTimeWeaver</code>被Spring用来在将类加载到Java虚拟机(JVM)中时动态地转换类</p>
<p>若要开启加载时织入,要在<code>@Configuration</code>类中增加<code>@EnableLoadTimeWeaving</code>注解，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableLoadTimeWeaving</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AppConfig</span> </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>或者，对于XML配置，您可以使用<code>context:load-time-weaver</code> 元素:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:load-time-weaver</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>一旦配置为 <code>ApplicationContext</code>,该 <code>ApplicationContext</code>中的任何bean都可以实现<code>LoadTimeWeaverAware</code>,从而接收对load-time weaver实例的引用。 这特别适用于<a href="https://github.com/DocsHome/spring-docs/blob/master/pages/dataaccess/data-access.md#orm-jpa" target="_blank" rel="noopener">Spring的JPA支持</a>。其中JPA类转换可能需要加载时织入。 有关更多详细信息，请参阅<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html" target="_blank" rel="noopener"><code>LocalContainerEntityManagerFactoryBean</code></a>.。 有关AspectJ加载时编织的更多信息，请参阅<a href="#aop-aj-ltw">Spring Framework中使用AspectJ的加载时织入</a>。</p>
<p><a id="context-introduction"></a></p>
<h3 id="1-15-ApplicationContext的附加功能"><a href="#1-15-ApplicationContext的附加功能" class="headerlink" title="1.15.ApplicationContext的附加功能"></a><a href="#context-introduction"></a>1.15.<code>ApplicationContext</code>的附加功能</h3><p>正如 <a href="#beans">前面章节</a>中讨论的，<code>org.springframework.beans.factory</code>包提供了管理和操作bean的基本功能，包括以编程方式。 <code>org.springframework.context</code>包添加了<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/ApplicationContext.html" target="_blank" rel="noopener"><code>ApplicationContext</code></a>接口，该接口扩展了<code>BeanFactory</code>接口，此外还扩展了其他接口，以更面向应用程序框架的方式提供其他功能。 许多人以完全声明的方式使用<code>ApplicationContext</code>， 甚至不以编程方式创建它，而是依赖于诸如<code>ContextLoader</code>之类的支持类来自动实例化<code>ApplicationContext</code>，作为Java EE Web应用程序的正常启动过程的一部分。</p>
<p>为了以更加面向框架的方式增强<code>BeanFactory</code>的功能,上下文包还提供了以下功能。</p>
<ul>
<li><p>通过<code>MessageSource</code>接口访问i18n风格的消息。</p>
</li>
<li><p>通过<code>ResourceLoader</code>接口访问URL和文件等资源。</p>
</li>
<li><p>事件发布，即通过使用<code>ApplicationEventPublisher</code>接口实现<code>ApplicationListener</code>接口的bean。</p>
</li>
<li><p>通过<code>HierarchicalBeanFactory</code>接口，加载多级contexts，允许关注某一层级context，比如应用的Web层。</p>
</li>
</ul>
<p><a id="context-functionality-messagesource"></a></p>
<h4 id="1-15-1-使用MessageSource实现国际化"><a href="#1-15-1-使用MessageSource实现国际化" class="headerlink" title="1.15.1. 使用MessageSource实现国际化"></a><a href="#context-functionality-messagesource"></a>1.15.1. 使用<code>MessageSource</code>实现国际化</h4><p><code>ApplicationContext</code> 接口扩展了一个名为<code>MessageSource</code>的接口，因此提供了国际化(“i18n”)功能。 Spring还提供了<code>HierarchicalMessageSource</code>接口，该接口可以分层次地解析消息。 这些接口共同提供了Spring影响消息解析的基础。 这些接口上定义的方法包括：</p>
<ul>
<li><p><code>String getMessage(String code, Object[] args, String default, Locale loc)</code>: 用于从<code>MessageSource</code>检索消息的基本方法。 如果未找到指定区域设置的消息，则使用默认消息。 传入的任何参数都使用标准库提供的<code>MessageFormat</code>功能成为替换值。</p>
</li>
<li><p><code>String getMessage(String code, Object[] args, Locale loc)</code>: 基本上与前一个方法相同，但有一个区别：不能指定默认消息。 如果找不到该消息，则抛出<code>NoSuchMessageException</code> 。</p>
</li>
<li><p><code>String getMessage(MessageSourceResolvable resolvable, Locale locale)</code>: 前面方法中使用的所有属性也包装在名为 <code>MessageSourceResolvable</code>的类中，您可以将此方法用于此类。</p>
</li>
</ul>
<p>当一个<code>ApplicationContext</code>被加载时,它会自动搜索在上下文中定义的一个<code>MessageSource</code>,bean必须包含名称<code>messageSource</code>,如果找到这样的bean 则将对前面方法的所有调用委派给消息源。如果没有找到消息源，<code>ApplicationContext</code>会尝试找到一个包含同名bean的父对象。如果有，它使用那个bean作为<code>MessageSource</code>。 如果<code>ApplicationContext</code>找不到消息的任何源，则会实例化空的<code>DelegatingMessageSource</code>，以便能够接受对上面定义的方法的调用。</p>
<p>Spring提供了两个MessageSource实现， <code>ResourceBundleMessageSource</code>和<code>StaticMessageSource</code>，为了做嵌套消息两者都实现了<code>HierarchicalMessageSource</code>。 <code>StaticMessageSource</code>很少使用，但提供了以编程方式向源添加消息。 以下示例显示了<code>ResourceBundleMessageSource</code>：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"messageSource"</span></span></span><br><span class="line"><span class="tag">            <span class="attr">class</span>=<span class="string">"org.springframework.context.support.ResourceBundleMessageSource"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"basenames"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">value</span>&gt;</span>format<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">value</span>&gt;</span>exceptions<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">value</span>&gt;</span>windows<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>该示例假定您在类路径中定义了三个资源包，<code>format</code>, <code>exceptions</code> and <code>windows</code>。任何解析消息的请求都将以JDK标准方式处理, 通过<code>ResourceBundle</code>解析消息。出于示例的目的，假设上述两个资源包文件的内容如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"># in format.properties</span><br><span class="line">message=Alligators rock!</span><br><span class="line"></span><br><span class="line"># in exceptions.properties</span><br><span class="line">argument.required=The &#123;<span class="number">0</span>&#125; argument is required.</span><br></pre></td></tr></table></figure>

<p>下一个示例显示了执行<code>MessageSource</code> 功能的程序。 请记住，所有<code>ApplicationContext</code>实现也都是<code>MessageSource</code> 实现，因此可以强制转换为<code>MessageSource</code> 接口。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    MessageSource resources = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"beans.xml"</span>);</span><br><span class="line">    String message = resources.getMessage(<span class="string">"message"</span>, <span class="keyword">null</span>, <span class="string">"Default"</span>, <span class="keyword">null</span>);</span><br><span class="line">    System.out.println(message);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述程序产生的结果如下:</p>
<p>Alligators rock!</p>
<p>总而言之，<code>MessageSource</code>在名为<code>beans.xml</code>的文件中定义，该文件存在于类路径的根目录中。<code>messageSource</code>bean定义通过其basenames属性引用许多资源包。 在列表中传递给<code>basenames</code>属性的三个文件作为类路径根目录下的文件存在，分别称为<code>format.properties</code>, <code>exceptions.properties</code>和<code>windows.properties</code>。</p>
<p>下一个示例显示传递给消息查询的参数，这些参数将被转换为字符串并插入查找消息中的占位符。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">&lt;beans&gt;</span><br><span class="line"></span><br><span class="line">    &lt;!-- <span class="keyword">this</span> MessageSource is being used in a web application --&gt;</span><br><span class="line">    &lt;bean id=<span class="string">"messageSource"</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">"org.springframework.context.support.ResourceBundleMessageSource"</span>&gt;</span><br><span class="line">        &lt;property name=<span class="string">"basename"</span> value=<span class="string">"exceptions"</span>/&gt;</span><br><span class="line">    &lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">    &lt;!-- lets inject the above MessageSource into <span class="keyword">this</span> POJO --&gt;</span><br><span class="line">    &lt;bean id=<span class="string">"example"</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">"com.something.Example"</span>&gt;</span><br><span class="line">        &lt;property name=<span class="string">"messages"</span> ref=<span class="string">"messageSource"</span>/&gt;</span><br><span class="line">    &lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">&lt;/beans&gt;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Example</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> MessageSource messages;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMessages</span><span class="params">(MessageSource messages)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.messages = messages;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String message = <span class="keyword">this</span>.messages.getMessage(<span class="string">"argument.required"</span>,</span><br><span class="line">            <span class="keyword">new</span> Object [] &#123;<span class="string">"userDao"</span>&#125;, <span class="string">"Required"</span>, <span class="keyword">null</span>);</span><br><span class="line">        System.out.println(message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用 <code>execute()</code>方法得到的结果如下:</p>
<p>The userDao argument is required.</p>
<p>关于国际化(“i18n”)，Spring的各种 <code>MessageSource</code>实现遵循与标准JDK <code>ResourceBundle</code>相同的区域设置解析和回退规则。 简而言之，继续前面定义的示例<code>messageSource</code>，如果要根据British(<code>en-GB</code>)语言环境解析消息，则应分别创建名为<code>format_en_GB.properties</code>，<code>exceptions_en_GB.properties</code>和<code>windows_en_GB.properties</code>的文件。</p>
<p>通常，区域设置解析由应用程序的环境配置管理。在以下示例中，手动指定解析（英国）消息的区域设置：</p>
<p># in exceptions_en_GB.properties<br>argument.required=Ebagum lad, the {0} argument is required, I say, required.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(<span class="keyword">final</span> String[] args)</span> </span>&#123;</span><br><span class="line">    MessageSource resources = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"beans.xml"</span>);</span><br><span class="line">    String message = resources.getMessage(<span class="string">"argument.required"</span>,</span><br><span class="line">        <span class="keyword">new</span> Object [] &#123;<span class="string">"userDao"</span>&#125;, <span class="string">"Required"</span>, Locale.UK);</span><br><span class="line">    System.out.println(message);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行上述程序产生的结果如下:</p>
<p>Ebagum lad, the ‘userDao’ argument is required, I say, required.</p>
<p>您还可以使用<code>MessageSourceAware</code>接口获取对已定义的任何<code>MessageSource</code>的引用。 在创建和配置bean时，应用程序上下文的<code>MessageSource</code>会注入实现<code>MessageSourceAware</code>接口的<code>ApplicationContext</code>中定义的任何bean。</p>
<p>作为<code>ResourceBundleMessageSource</code>的替代，Spring提供了一个<code>ReloadableResourceBundleMessageSource</code>类。 此变体支持相同的bundle文件格式，但比基于标准JDK的<code>ResourceBundleMessageSource</code>实现更灵活。特别是，它允许从任何Spring资源位置（不仅从类路径）读取文件，并支持bundle属性文件的热重新加载（同时在其间有效地缓存它们）。 有关详细信息，请参阅<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/support/ReloadableResourceBundleMessageSource.html" target="_blank" rel="noopener"><code>ReloadableResourceBundleMessageSource</code></a> javadoc。</p>
<p><a id="context-functionality-events"></a></p>
<h4 id="1-15-2-标准和自定义事件"><a href="#1-15-2-标准和自定义事件" class="headerlink" title="1.15.2. 标准和自定义事件"></a><a href="#context-functionality-events"></a>1.15.2. 标准和自定义事件</h4><p><code>ApplicationContext</code>中的事件处理是通过<code>ApplicationEvent</code>类和<code>ApplicationListener</code>接口提供的。如果将实现<code>ApplicationListener</code>接口的bean部署到上下文中，则每次将<code>ApplicationEvent</code>发布到<code>ApplicationContext</code>时，都会通知该bean。 从本质上讲，这是标准的Observer设计模式。</p>
<p>从Spring 4.2开始，事件架构已经得到显着改进，并提供了一个<a href="#context-functionality-events-annotation">基于注解的模型</a>使其有发布任意事件的能力（即，不一定从<code>ApplicationEvent</code>扩展的对象） 。当发布这样的对象时，我们将它包装在一个事件中。</p>
<p>下表描述了Spring提供的标准事件：:</p>
<p>Table 7. Built-in Events</p>
<table>
<thead>
<tr>
<th>事件</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td><code>ContextRefreshedEvent</code></td>
<td>初始化或刷新<code>ApplicationContext</code>时发布（例如，通过使用<code>ConfigurableApplicationContext</code> 接口上的<code>refresh()</code> 方法）。 这里，“initialized”意味着加载所有bean，检测并激活bean的后置处理器，预先实例化单例，并且可以使用<code>ApplicationContext</code>对象。 只要上下文尚未关闭，只要所选的<code>ApplicationContext</code>实际支持这种“热”刷新，就可以多次触发刷新。 例如，<code>XmlWebApplicationContext</code>支持热刷新，但<code>GenericApplicationContext</code> 不支持。</td>
</tr>
<tr>
<td><code>ContextStartedEvent</code></td>
<td>通过使用<code>ConfigurableApplicationContext</code>接口上的<code>start()</code>方法启动<code>ApplicationContext</code> 时发布。 通常，此信号用于在显式停止后重新启动Bean，但它也可用于启动尚未为自动启动配置的组件（例如，在初始化时尚未启动的组件）。</td>
</tr>
<tr>
<td><code>ContextStoppedEvent</code></td>
<td>通过使用<code>ConfigurableApplicationContext</code>接口上的<code>close()</code> 方法停止<code>ApplicationContext</code>时发布。 这里，“已停止”表示所有生命周期bean都会收到明确的停止信号。 可以通过<code>start()</code>调用重新启动已停止的上下文。</td>
</tr>
<tr>
<td><code>ContextClosedEvent</code></td>
<td>通过使用<code>ConfigurableApplicationContext</code>接口上的<code>close()</code>方法关闭<code>ApplicationContext</code>时发布。 这里， “关闭” 意味着所有单例bean都被销毁。 封闭的环境达到其寿命终结。 它无法刷新或重新启动。</td>
</tr>
<tr>
<td><code>RequestHandledEvent</code></td>
<td>一个特定于Web的事件，告诉所有bean已经为HTTP请求提供服务。 请求完成后发布此事件。 此事件仅适用于使用Spring的DispatcherServlet的Web应用程序。</td>
</tr>
</tbody></table>
<p>您还可以创建和发布自己的自定义事件。 以下示例显示了一个扩展Spring的<code>ApplicationEvent</code>基类的简单类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BlackListEvent</span> <span class="keyword">extends</span> <span class="title">ApplicationEvent</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> String address;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> String content;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BlackListEvent</span><span class="params">(Object source, String address, String content)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(source);</span><br><span class="line">        <span class="keyword">this</span>.address = address;</span><br><span class="line">        <span class="keyword">this</span>.content = content;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// accessor and other methods...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>要发布自定义<code>ApplicationEvent</code>，请在<code>ApplicationEventPublisher</code>上调用<code>publishEvent()</code>方法。 通常，这是通过创建一个实现 <code>ApplicationEventPublisherAware</code>并将其注册为Spring bean的类来完成的。 以下示例显示了这样一个类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EmailService</span> <span class="keyword">implements</span> <span class="title">ApplicationEventPublisherAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> List&lt;String&gt; blackList;</span><br><span class="line">    <span class="keyword">private</span> ApplicationEventPublisher publisher;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBlackList</span><span class="params">(List&lt;String&gt; blackList)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.blackList = blackList;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationEventPublisher</span><span class="params">(ApplicationEventPublisher publisher)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.publisher = publisher;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sendEmail</span><span class="params">(String address, String content)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (blackList.contains(address)) &#123;</span><br><span class="line">            publisher.publishEvent(<span class="keyword">new</span> BlackListEvent(<span class="keyword">this</span>, address, content));</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// send email...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在配置时，Spring容器检测到<code>EmailService</code>实现<code>ApplicationEventPublisherAware</code>并自动调用<code>setApplicationEventPublisher()</code>。 实际上，传入的参数是Spring容器本身。 您正在通过其<code>ApplicationEventPublisher</code>接口与应用程序上下文进行交互。</p>
<p>要接收自定义 <code>ApplicationEvent</code>，您可以创建一个实现<code>ApplicationListener</code>的类并将其注册为Spring bean。 以下示例显示了这样一个类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BlackListNotifier</span> <span class="keyword">implements</span> <span class="title">ApplicationListener</span>&lt;<span class="title">BlackListEvent</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String notificationAddress;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNotificationAddress</span><span class="params">(String notificationAddress)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.notificationAddress = notificationAddress;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onApplicationEvent</span><span class="params">(BlackListEvent event)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// notify appropriate parties via notificationAddress...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>请注意，<code>ApplicationListener</code>通常使用自定义事件的类型进行参数化（前面示例中为<code>BlackListEvent</code>）。这意味着<code>onApplicationEvent()</code>方法可以保持类型安全，从而避免任何向下转换的需要。 您可以根据需要注册任意数量的事件侦听器，但请注意，默认情况下，事件侦听器会同步接收事件。这意味着<code>publishEvent()</code>方法将阻塞，直到所有侦听器都已完成对事件的处理。 这种同步和单线程方法的一个优点是，当侦听器接收到事件时，如果事务上下文可用，它将在发布者的事务上下文内运行。如果需要另一个事件发布策略，请参阅Spring的<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/context/event/ApplicationEventMulticaster.html" target="_blank" rel="noopener"><code>ApplicationEventMulticaster</code></a>接口的javadoc。</p>
<p>以下示例显示了用于注册和配置上述每个类的bean定义:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"emailService"</span> <span class="attr">class</span>=<span class="string">"example.EmailService"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"blackList"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>[email protected]<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>[email protected]<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">value</span>&gt;</span>[email protected]<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"blackListNotifier"</span> <span class="attr">class</span>=<span class="string">"example.BlackListNotifier"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"notificationAddress"</span> <span class="attr">value</span>=<span class="string">"[email protected]"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>总而言之，当调用<code>emailService</code> bean的<code>sendEmail()</code>方法时，如果有任何应列入黑名单的电子邮件消息，则会发布<code>BlackListEvent</code>类型的自定义事件。 <code>blackListNotifier</code> bean注册为<code>ApplicationListener</code> 并接收<code>BlackListEvent</code> ，此时它可以通知相关方。</p>
<p>Spring的事件机制是为在同一应用程序上下文中的Spring bean之间的简单通信而设计的。但是，对于更复杂的企业集成需求，单独维护的<a href="https://projects.spring.io/spring-integration/" target="_blank" rel="noopener">Spring Integration</a> 项目提供了完整的支持并可用于构建轻量级，<a href="http://www.enterpriseintegrationpatterns.com" target="_blank" rel="noopener">pattern-oriented</a>(面向模式），依赖Spring编程模型的事件驱动架构。</p>
<p><a id="context-functionality-events-annotation"></a></p>
<h5 id="基于注解的事件监听器"><a href="#基于注解的事件监听器" class="headerlink" title="基于注解的事件监听器"></a><a href="#context-functionality-events-annotation"></a>基于注解的事件监听器</h5><p>从Spring 4.2开始，您可以使用<code>EventListener</code>注解在托管bean的任何公共方法上注册事件监听器。 <code>BlackListNotifier</code>可以重写如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BlackListNotifier</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String notificationAddress;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNotificationAddress</span><span class="params">(String notificationAddress)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.notificationAddress = notificationAddress;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@EventListener</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">processBlackListEvent</span><span class="params">(BlackListEvent event)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// notify appropriate parties via notificationAddress...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>方法签名再次声明它侦听的事件类型，但这次使用灵活的名称并且没有实现特定的侦听器接口。只要实际事件类型在其实现层次结构中解析通用参数，也可以通过泛型缩小事件类型。</p>
<p>如果您的方法应该监听多个事件，或者您想要根据任何参数进行定义，那么也可以在注解本身上指定事件类型。 以下示例显示了如何执行此操作：:</p>
<pre><code>@EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})
public void handleContextStart() {
    ...
}</code></pre><p>还可以通过使用定义<a href="#expressions"><code>SpEL</code> 表达式</a>的注解的<code>condition</code>属性来添加额外的运行时过滤，该表达式应匹配以实际调用特定事件的方法。</p>
<p>以下示例显示了仅当事件的<code>content</code>属性等于<code>my-event</code>时才能重写我们的通知程序以进行调用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EventListener</span>(condition = <span class="string">"#blEvent.content == 'my-event'"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">processBlackListEvent</span><span class="params">(BlackListEvent blEvent)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// notify appropriate parties via notificationAddress...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>每个<code>SpEL</code>表达式都针对专用上下文进行评估。 下表列出了可用于上下文的项目，以便您可以将它们用于条件事件处理：</p>
<p>Table 8. 事件SpEL可用的元数据</p>
<table>
<thead>
<tr>
<th>名字</th>
<th>位置</th>
<th>描述</th>
<th>例子</th>
</tr>
</thead>
<tbody><tr>
<td>Event</td>
<td>root</td>
<td>实际<code>ApplicationEvent</code></td>
<td><code>#root.event</code></td>
</tr>
<tr>
<td>Arguments array</td>
<td>root object</td>
<td>用于调用目标的参数（作为数组）</td>
<td><code>#root.args[0]</code></td>
</tr>
<tr>
<td><em>Argument name</em></td>
<td>evaluation context</td>
<td>任何方法参数的名称。 如果由于某种原因，名称不可用（例如，因为没有调试信息），参数名称也可以在#a <code>#a&lt;#arg&gt;</code>下获得，其中<code>#arg</code>代表参数索引（从0开始）。</td>
<td><code>#blEvent</code> or <code>#a0</code> (you can also use <code>#p0</code> or <code>#p&lt;#arg&gt;</code> notation as an alias)</td>
</tr>
</tbody></table>
<p>请注意，即使您的方法签名实际引用已发布的任意对象，<code>#root.event</code>也允许您访问基础事件。</p>
<p>如果需要发布一个事件作为处理另一个事件的结果，则可以更改方法签名以返回应发布的事件，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EventListener</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ListUpdateEvent <span class="title">handleBlackListEvent</span><span class="params">(BlackListEvent event)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// notify appropriate parties via notificationAddress and</span></span><br><span class="line">    <span class="comment">// then publish a ListUpdateEvent...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a href="#context-functionality-events-async">异步侦听器</a>不支持此功能。</p>
<p>这将通过上述方法处理每个<code>BlackListEvent</code>并发布一个新的<code>ListUpdateEvent</code>，如果需要发布多个事件，则可以返回事件 <code>集合</code>。</p>
<p><a id="context-functionality-events-async"></a></p>
<h5 id="异步的监听器"><a href="#异步的监听器" class="headerlink" title="异步的监听器"></a><a href="#context-functionality-events-async"></a>异步的监听器</h5><p>如果希望特定侦听器异步处理事件，则可以重用<a href="https://github.com/DocsHome/spring-docs/blob/master/pages/integration/integration.md#scheduling-annotation-support-async" target="_blank" rel="noopener">常规 <code>@Async</code>支持</a>。 以下示例显示了如何执行此操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EventListener</span></span><br><span class="line"><span class="meta">@Async</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">processBlackListEvent</span><span class="params">(BlackListEvent event)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// BlackListEvent is processed in a separate thread</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用异步事件时请注意以下限制:</p>
<ul>
<li><p>如果事件侦听器抛出<code>Exception</code>，则不会将其传播给调用者。有关更多详细信息，请参阅 <code>AsyncUncaughtExceptionHandler</code>。</p>
</li>
<li><p>此类事件监听器无法发送回复。 如果您需要作为处理结果发送另一个事件，请注入<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/aop/interceptor/AsyncUncaughtExceptionHandler.html" target="_blank" rel="noopener"><code>ApplicationEventPublisher</code></a>以手动发送事件。</p>
</li>
</ul>
<p><a id="context-functionality-events-order"></a></p>
<h5 id="监听器的排序"><a href="#监听器的排序" class="headerlink" title="监听器的排序"></a><a href="#context-functionality-events-order"></a>监听器的排序</h5><p>如果需要在另一个侦听器之前调用一个侦听器，则可以将<code>@Order</code>注解添加到方法声明中，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EventListener</span></span><br><span class="line"><span class="meta">@Order</span>(<span class="number">42</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">processBlackListEvent</span><span class="params">(BlackListEvent event)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// notify appropriate parties via notificationAddress...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a id="context-functionality-events-generics"></a></p>
<h5 id="泛型的事件"><a href="#泛型的事件" class="headerlink" title="泛型的事件"></a><a href="#context-functionality-events-generics"></a>泛型的事件</h5><p>您还可以使用泛型来进一步定义事件的结构。 考虑使用<code>EntityCreatedEvent&lt;T&gt;</code>，其中<code>T</code>是创建的实际实体的类型。 例如，您可以创建以下侦听器定义以仅接收<code>Person</code>的<code>EntityCreatedEvent</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EventListener</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onPersonCreated</span><span class="params">(EntityCreatedEvent&lt;Person&gt; event)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由于泛型擦除，只有此事件符合事件监听器所过滤的通用参数条件那么才会触发相应的处理事件(有点类似于<code>class PersonCreatedEvent extends EntityCreatedEvent&lt;Person&gt; { … }</code>）</p>
<p>在某些情况下，如果所有事件遵循相同的结构(如上述事件的情况），这可能变得相当乏味。在这种情况下，开发者可以实现<code>ResolvableTypeProvider</code>来引导框架超出所提供的运行时环境范围。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EntityCreatedEvent</span>&lt;<span class="title">T</span>&gt; <span class="keyword">extends</span> <span class="title">ApplicationEvent</span> <span class="keyword">implements</span> <span class="title">ResolvableTypeProvider</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">EntityCreatedEvent</span><span class="params">(T entity)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(entity);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ResolvableType <span class="title">getResolvableType</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> ResolvableType.forClassWithGenerics(getClass(), ResolvableType.forInstance(getSource()));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这不仅适用于<code>ApplicationEvent</code> ，也适用于作为事件发送的任意对象。</p>
<p><a id="context-functionality-resources"></a></p>
<h4 id="1-15-3-通过便捷的方式访问底层资源"><a href="#1-15-3-通过便捷的方式访问底层资源" class="headerlink" title="1.15.3.通过便捷的方式访问底层资源"></a><a href="#context-functionality-resources"></a>1.15.3.通过便捷的方式访问底层资源</h4><p>为了最佳地使用和理解应用程序上下文，您应该熟悉Spring的资源抽象，如参考资料中所述<a href="#resources">资源</a>。</p>
<p>应用程序上下文是<code>ResourceLoader</code>，可用于加载<code>Resource</code>对象。 <code>Resource</code>本质上是JDK<code>java.net.URL</code>类的功能更丰富的版本。实际上Resource的实现类中大多含有<code>java.net.URL</code>的实例。 <code>Resource</code>几乎能从任何地方透明的获取底层资源，可以是classpath类路径、文件系统、标准的URL资源及变种URL资源。如果资源定位字串是简单的路径， 没有任何特殊前缀，就适合于实际应用上下文类型。</p>
<p>可以配置一个bean部署到应用上下文中，用以实现特殊的回调接口，<code>ResourceLoaderAware</code>它会在初始化期间自动回调。应用程序上下文本身作为<code>ResourceLoader</code>传入。可以公开<code>Resource</code>的type属性，这样就可以访问静态资源 静态资源可以像其他properties那样被注入<code>Resource</code>。可以使用简单的字串路径指定资源，这需要依赖于特殊的JavaBean <code>PropertyEditor</code>（由上下文自动注册），当bean部署时候它将转换资源中的字串为实际的资源对象。</p>
<p>提供给<code>ApplicationContext</code>构造函数的一个或多个位置路径实际上是资源字符串，并且以简单形式对特定上下文实现进行适当处理。 <code>ClassPathXmlApplicationContext</code>将一个简单的定位路径视为类路径位置。开发者还可以使用带有特殊前缀的定位路径，这样就可以强制从classpath或者URL定义加载路径， 而不用考虑实际的上下文类型。</p>
<p><a id="context-create"></a></p>
<h4 id="1-15-4-快速对Web应用的ApplicationContext实例化"><a href="#1-15-4-快速对Web应用的ApplicationContext实例化" class="headerlink" title="1.15.4. 快速对Web应用的ApplicationContext实例化"></a><a href="#context-create"></a>1.15.4. 快速对Web应用的ApplicationContext实例化</h4><p>开发者可以通过使用<code>ContextLoader</code>来声明性地创建<code>ApplicationContext</code>实例，当然也可以通过使用<code>ApplicationContext</code>的实现来编程实现<code>ApplicationContext</code>。</p>
<p>您可以使用<code>ContextLoaderListener</code>注册<code>ApplicationContext</code> ，如以下示例所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">context-param</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">context-param</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">listener</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">listener-class</span>&gt;</span>org.springframework.web.context.ContextLoaderListener<span class="tag">&lt;/<span class="name">listener-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">listener</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>侦听器检查<code>contextConfigLocation</code>参数。 如果参数不存在，则侦听器将<code>/WEB-INF/applicationContext.xml</code>用作默认值。 当参数确实存在时，侦听器使用预定义的分隔符（逗号，分号和空格）分隔String，并将值用作搜索应用程序上下文的位置。 还支持Ant样式的路径模式。 示例是<code>/WEB-INF/*Context.xml</code>（对于所有名称以<code>Context.xml</code>结尾且位于<code>WEB-INF</code> 目录中的文件）和<code>/WEB-INF/**/*Context.xml</code>（对于所有这样的文件） <code>WEB-INF</code>的任何子目录中的文件。</p>
<p><a id="context-deploy-rar"></a></p>
<h4 id="1-15-5-使用Java-EE-RAR文件部署Spring的ApplicationContext"><a href="#1-15-5-使用Java-EE-RAR文件部署Spring的ApplicationContext" class="headerlink" title="1.15.5. 使用Java EE RAR文件部署Spring的ApplicationContext"></a><a href="#context-deploy-rar"></a>1.15.5. 使用Java EE RAR文件部署Spring的<code>ApplicationContext</code></h4><p>可以将Spring <code>ApplicationContext</code>部署为RAR文件，将上下文及其所有必需的bean类和库JAR封装在Java EE RAR部署单元中，这相当于引导一个独立的<code>ApplicationContext</code>。 只是托管在Java EE环境中，能够访问Java EE服务器设施。在部署无头WAR文件(实际上，没有任何HTTP入口点，仅用于在Java EE环境中引导Spring <code>ApplicationContext</code>的WAR文件）的情况下RAR部署是更自然的替代方案</p>
<p>RAR部署非常适合不需要HTTP入口点但仅由消息端点和调度作业组成的应用程序上下文。在这种情况下，Bean可以使用应用程序服务器资源， 例如JTA事务管理器和JNDI绑定的JDBC <code>DataSource</code>和JMS <code>ConnectionFactory</code>实例，并且还可以通过Spring的标准事务管理和JNDI和JMX支持设施向平台的JMX服务器注册。 应用程序组件还可以通过Spring的<code>TaskExecutor</code>抽象实现与应用程序服务器的JCA <code>WorkManager</code> 交互</p>
<p>有关RAR部署中涉及的配置详细信息，请参阅 <a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/jca/context/SpringContextResourceAdapter.html" target="_blank" rel="noopener"><code>SpringContextResourceAdapter</code></a>类的javadoc</p>
<p>对于将Spring ApplicationContext简单部署为Java EE RAR文件：</p>
<ol>
<li><p>将所有应用程序类打包到一个RAR文件（这是一个具有不同文件扩展名的标准JAR文件）。将所有必需的库JAR添加到RAR存档的根目录中。 。添加<code>META-INF/ra.xml</code>部署描述符 （如<a href="https://docs.spring.io/spring-framework/docs/5.1.3.BUILD-SNAPSHOT/javadoc-api/org/springframework/jca/context/SpringContextResourceAdapter.html" target="_blank" rel="noopener"><code>SpringContextResourceAdapter</code></a>的javadoc所示） 和相应的Spring XML bean定义文件（通常是 META-INF/applicationContext.xml）。</p>
</li>
<li><p>将生成的RAR文件放入应用程序服务器的部署目录中。</p>
</li>
</ol>
<p>这种RAR部署单元通常是独立的。它们不会将组件暴露给外部世界，甚至不会暴露给同一应用程序的其他模块。 与基于RAR的<code>ApplicationContext</code>的交互通常通过与其他模块共享的JMS目标进行。 例如，基于RAR的<code>ApplicationContext</code>还可以调度一些作业或对文件系统（等等）中的新文件作出反应。 如果它需要允许来自外部的同步访问，它可以（例如）导出RMI端点，这可以由同一台机器上的其他应用程序模块使用。</p>
<p><a id="beans-beanfactory"></a></p>
<h3 id="1-16-BeanFactory"><a href="#1-16-BeanFactory" class="headerlink" title="1.16.BeanFactory"></a><a href="#beans-beanfactory"></a>1.16.<code>BeanFactory</code></h3><p><code>BeanFactory</code> API为Spring的IoC功能提供了基础。 它的特定契约主要用于与Spring的其他部分和相关的第三方框架集成其<code>DefaultListableBeanFactory</code>实现是更高级别<code>GenericApplicationContext</code>容器中的密钥委托。</p>
<p><code>BeanFactory</code>和相关接口（例如<code>BeanFactoryAware</code>, <code>InitializingBean</code>，<code>DisposableBean</code>）是其他框架组件的重要集成点。 通过不需要任何注解或甚至反射，它们允许容器与其组件之间的非常有效的交互。 应用程序级bean可以使用相同的回调接口，但通常更喜欢通过注解或通过编程配置进行声明性依赖注入。</p>
<p>请注意，核心<code>BeanFactory</code> API级别及其 <code>DefaultListableBeanFactory</code>实现不会对配置格式或要使用的任何组件注解做出假设。 所有这些风格都通过扩展（例如<code>XmlBeanDefinitionReader</code>和<code>AutowiredAnnotationBeanPostProcessor</code>）进行，并作为核心元数据表示在共享<code>BeanDefinition</code>对象上运行。 这是使Spring的容器如此灵活和可扩展的本质。</p>
<p><a id="context-introduction-ctx-vs-beanfactory"></a></p>
<h4 id="1-16-1-选择BeanFactory还是ApplicationContext"><a href="#1-16-1-选择BeanFactory还是ApplicationContext" class="headerlink" title="1.16.1. 选择BeanFactory还是ApplicationContext?"></a><a href="#context-introduction-ctx-vs-beanfactory"></a>1.16.1. 选择<code>BeanFactory</code>还是<code>ApplicationContext</code>?</h4><p>本节介绍<code>BeanFactory</code>和<code>ApplicationContext</code>容器级别之间的差异以及影响。</p>
<p>您应该使用<code>ApplicationContext</code>，除非您有充分的理由不这样做，使用<code>GenericApplicationContext</code>及其子类<code>AnnotationConfigApplicationContext</code>作为自定义引导的常见实现。 这些是Spring用于所有常见目的的核心容器的主要入口点：加载配置文件，触发类路径扫描，以编程方式注册bean定义和带注解的类，以及（从5.0开始）注册功能bean定义。</p>
<p>因为<code>ApplicationContext</code>包括<code>BeanFactory</code>的所有功能，和<code>BeanFactory</code>相比更值得推荐，除了一些特定的场景，例如在资源受限的设备上运行的内嵌的应用。 在<code>ApplicationContext</code>（例如<code>GenericApplicationContext</code>实现）中，按照约定（即通过bean名称或bean类型 - 特别是后处理器）检测到几种bean， 而普通的<code>DefaultListableBeanFactory</code>对任何特殊bean都是不可知的。</p>
<p>对于许多扩展容器功能，例如注解处理和AOP代理， <a href="#beans-factory-extension-bpp"><code>BeanPostProcessor</code>扩展点是必不可少的。如果仅使用普通的<code>DefaultListableBeanFactory</code>，则默认情况下不会检测到并激活此类后置处理器。 这种情况可能令人困惑，因为您的bean配置实际上没有任何问题。 相反，在这种情况下，容器需要至少得多一些额外的处理。</a></p>
<p>下表列出了<code>BeanFactory</code>和<code>ApplicationContext</code>接口和实现提供的功能。</p>
<p>Table 9.特性矩阵  </p>
<table>
<thead>
<tr>
<th>Feature</th>
<th><code>BeanFactory</code></th>
<th><code>ApplicationContext</code></th>
</tr>
</thead>
<tbody><tr>
<td>Bean Bean实例化/装配</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>集成的生命周期管理</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>自动注册 <code>BeanPostProcessor</code></td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>自动注册 <code>BeanFactoryPostProcessor</code></td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>便利的 <code>MessageSource</code> 访问 (国际化)</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>内置<code>ApplicationEvent</code> 发布机制</td>
<td>No</td>
<td>Yes</td>
</tr>
</tbody></table>
<p>要使用 <code>DefaultListableBeanFactory</code>显式注册bean的后置处理器，您需要以编程方式调用 <code>addBeanPostProcessor</code>，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">DefaultListableBeanFactory factory = <span class="keyword">new</span> DefaultListableBeanFactory();</span><br><span class="line"><span class="comment">// populate the factory with bean definitions</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// now register any needed BeanPostProcessor instances</span></span><br><span class="line">factory.addBeanPostProcessor(<span class="keyword">new</span> AutowiredAnnotationBeanPostProcessor());</span><br><span class="line">factory.addBeanPostProcessor(<span class="keyword">new</span> MyBeanPostProcessor());</span><br><span class="line"></span><br><span class="line"><span class="comment">// now start using the factory</span></span><br></pre></td></tr></table></figure>

<p>要将<code>BeanFactoryPostProcessor</code> 应用于普通的<code>DefaultListableBeanFactory</code>，需要调用其<code>postProcessBeanFactory</code>方法，如以下示例所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">DefaultListableBeanFactory factory = <span class="keyword">new</span> DefaultListableBeanFactory();</span><br><span class="line">XmlBeanDefinitionReader reader = <span class="keyword">new</span> XmlBeanDefinitionReader(factory);</span><br><span class="line">reader.loadBeanDefinitions(<span class="keyword">new</span> FileSystemResource(<span class="string">"beans.xml"</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">// bring in some property values from a Properties file</span></span><br><span class="line">PropertyPlaceholderConfigurer cfg = <span class="keyword">new</span> PropertyPlaceholderConfigurer();</span><br><span class="line">cfg.setLocation(<span class="keyword">new</span> FileSystemResource(<span class="string">"jdbc.properties"</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">// now actually do the replacement</span></span><br><span class="line">cfg.postProcessBeanFactory(factory);</span><br></pre></td></tr></table></figure>

<p>在这两种情况下，显示注册步骤都不方便，这就是为什么各种<code>ApplicationContext</code>变体优先于Spring支持的应用程序中的普通<code>DefaultListableBeanFactory</code>， 尤其是在典型企业设置中依赖<code>BeanFactoryPostProcessor</code> 和 <code>BeanPostProcessor</code>实例来扩展容器功能时。</p>
<p><code>AnnotationConfigApplicationContext</code>具有注册的所有常见注解后置处理器，并且可以通过配置注解（例如<code>@EnableTransactionManagement</code>）在封面下引入其他处理器。 在Spring的基于注解的配置模型的抽象级别，bean的后置处理器的概念变成仅仅是内部容器细节。</p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://dxysun.com/2020/12/13/springForIocContainer/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/spring/" rel="tag">spring</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/12/13/springForResources/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            2、Spring 资源
          
        </div>
      </a>
    
    
      <a href="/2020/12/13/springForMvc/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Spring Web MVC</div>
      </a>
    
  </nav>

  
   
  
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2024
        <i class="ri-heart-fill heart_icon"></i> dxysun
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
        <li>
          <a href="https://beian.miit.gov.cn" target="_black" rel="nofollow">豫ICP备17012675号-1</a>
        </li>
        
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="https://dxysun.com/static/logo.png" alt="迎着朝阳"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/photos">相册</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://tu.dxysun.com/alipay-20201219151322.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://tu.dxysun.com/weixin-20201219151346.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
  var ayerConfig = {
    mathjax: true
  }
</script>

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


<script src="/js/dz.js"></script>



    
  </div>
</body>

</html>